forked from elixered/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path653-two-sum-iv-input-is-a-bst.cpp
55 lines (55 loc) · 1.36 KB
/
653-two-sum-iv-input-is-a-bst.cpp
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
stack<TreeNode*> st1, st2;
auto t1 = root, t2 = root;
while(1)
{
while(t1)
{
st1.push(t1);
t1 = t1->left;
}
while(t2)
{
st2.push(t2);
t2 = t2->right;
}
if(st1.empty() or st2.empty())
return false;
t1 = st1.top();
t2 = st2.top();
int curr = t1->val + t2->val;
if(curr==k)
{
if(t1!=t2)
return true;
else return false;
}
else if(curr>k)
{
t2 = st2.top()->left;
st2.pop();
t1 = NULL;
}
else
{
t1 = st1.top()->right;
t2 =NULL;
st1.pop();
}
}
return false;
}
};