-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLowest Common Ancestor of a Binary Tree.cpp
48 lines (44 loc) · 1.23 KB
/
Lowest Common Ancestor of a Binary Tree.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
/**
* 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:
vector<TreeNode*> ans;
void getAncestor(TreeNode* temp,vector<TreeNode*> vec,TreeNode* search)
{
if(temp==NULL)
return ;
if(temp->left == search || temp->right==search)
{
vec.push_back(temp);
vec.push_back(search);
ans=vec;
return ;
}
vec.push_back(temp);
getAncestor(temp->left,vec,search);
getAncestor(temp->right,vec,search);
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL)
return root;
if(root==p || root==q)
return root;
TreeNode* lefty=lowestCommonAncestor(root->left,p,q);
TreeNode* righty=lowestCommonAncestor(root->right,p,q);
if(lefty!=NULL && righty!=NULL)
return root;
else{
if(lefty!=NULL)
return lefty;
return righty;
}
//return root;
}
};