-
Notifications
You must be signed in to change notification settings - Fork 0
/
lowest_common_ancestor.cpp
62 lines (61 loc) · 1.54 KB
/
lowest_common_ancestor.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
56
57
58
59
60
61
62
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
vector<TreeNode *> stack;
TreeNode *ret;
int x=-1,y=-1,top=-1;
TreeNode *current = root;
int found = 0;
while(current!=NULL)
{
stack.push_back(current);
top++;
if(current == p || current == q)
{
if(y==-1)
{
x=top;
y=1;
ret=stack[x];
}
cout<<"lca ind:"<<x<<"\n";
found++;
}
if(found == 2)
return ret;
if(current->left==NULL)
{
while(top>=0)
{
current = stack[top];
top--;
if(y==1 && x>top)
{
ret=stack[x];
x=top;
}
stack.pop_back();
if(current->right != NULL)
{
break;
}
}
current=current->right;
continue;
}
current=current->left;
}
if(found==2)
return ret;
return NULL;
}
};