-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path2-Sum Binary Tree.cpp
More file actions
59 lines (54 loc) · 1.15 KB
/
2-Sum Binary Tree.cpp
File metadata and controls
59 lines (54 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTiterator
{
stack<TreeNode*> st;
bool reverse;
void pushAll(TreeNode* root){
while(root!= NULL){
st.push(root);
if(!reverse) root = root->left;
else root = root->right;
}
}
public:
BSTiterator(TreeNode *root, bool rev)
{
reverse = rev;
pushAll(root);
}
int next()
{
TreeNode* root = st.top();
st.pop();
if(!reverse) pushAll(root->right);
else pushAll(root->left);
return root->val;
}
bool hasNext()
{
return !st.empty();
}
};
int Solution::t2Sum(TreeNode* root, int k) {
if(!root) return false;
BSTiterator l(root, false);
BSTiterator r(root, true);
int i = l.next();
int j = r.next();
while(i<j){
if(i+j == k) return true;
if(i+j < k)
i = l.next();
else
j = r.next();
}
return false;
}