-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2SumBinaryTree.cpp
More file actions
55 lines (55 loc) · 1.31 KB
/
2SumBinaryTree.cpp
File metadata and controls
55 lines (55 loc) · 1.31 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
#include<iostream>
#include<stack>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void traverseLeft(std::stack<TreeNode*> &st, TreeNode* root){
while(root){
st.push(root);
root=root->left;
}
}
void traverseRight(std::stack<TreeNode*> &st, TreeNode* root){
while(root){
st.push(root);
root = root->right;
}
}
int t2Sum(TreeNode* A, int B) {
//use two pointers approach
//use inorder and reverse inorder
TreeNode* t1,*t2;
//st1 will be used for forward inorder traversal;
//st2 will be used for reverse inorder traversal;
std::stack<TreeNode*> st1,st2;
traverseLeft(st1,A);
traverseRight(st2,A);
while(st1.top()!=st2.top()){
TreeNode* i1 = st1.top();
TreeNode* i2 = st2.top();
if(i1==i2){
break;
}
int currSum = i1->val + i2->val;
if(currSum==B){
return 1;
}
else if(currSum>B){
//decrement i2 ptr
st2.pop();
if(i2->left){
traverseRight(st2,i2->left);
}
}
else{
st1.pop();
if(i1->right){
traverseLeft(st1, i1->right);
}
}
}
return 0;
}