Skip to content

Commit 75b83d2

Browse files
Create two_sum_in_bst_iv.cpp
1 parent 32701e6 commit 75b83d2

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

two_sum_in_bst_iv.cpp

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
13+
class BSTIterator {
14+
15+
stack<TreeNode*> st;
16+
bool reverse;
17+
18+
void partialInorder(TreeNode *root) {
19+
while(root) {
20+
st.push(root);
21+
root = !reverse ? root->left : root->right;
22+
}
23+
}
24+
public:
25+
BSTIterator(TreeNode *root, bool reverse = false) : reverse(reverse) {
26+
partialInorder(root);
27+
}
28+
29+
int next() {
30+
auto next = st.top();
31+
st.pop();
32+
33+
auto itr = !reverse ? next->right : next->left; //for leftItr(check right subtree) and inverse for other
34+
if(itr) {
35+
partialInorder(itr);
36+
}
37+
return next->val;
38+
}
39+
};
40+
41+
/*based on approach mentioned here - https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/1420711*/
42+
/*TC: O(n) | SC: O(h)*/
43+
class Solution {
44+
public:
45+
bool findTarget(TreeNode* root, int k) {
46+
BSTIterator leftItr(root), rightItr(root, true);
47+
int left = leftItr.next(), right = rightItr.next();
48+
49+
while(left < right) {
50+
if(left + right == k) return true;
51+
if(left + right < k)
52+
left = leftItr.next();
53+
else
54+
right = rightItr.next();
55+
}
56+
return false;
57+
}
58+
};

0 commit comments

Comments
 (0)