Skip to content

Commit 77d9085

Browse files
authored
Create Lowest Common Ancestor of a Binary Tree.cpp
1 parent 3e7eae9 commit 77d9085

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
vector<TreeNode*> ans;
13+
void getAncestor(TreeNode* temp,vector<TreeNode*> vec,TreeNode* search)
14+
{
15+
if(temp==NULL)
16+
return ;
17+
if(temp->left == search || temp->right==search)
18+
{
19+
vec.push_back(temp);
20+
vec.push_back(search);
21+
ans=vec;
22+
return ;
23+
}
24+
vec.push_back(temp);
25+
getAncestor(temp->left,vec,search);
26+
getAncestor(temp->right,vec,search);
27+
}
28+
29+
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
30+
if(root==NULL)
31+
return root;
32+
33+
if(root==p || root==q)
34+
return root;
35+
36+
TreeNode* lefty=lowestCommonAncestor(root->left,p,q);
37+
TreeNode* righty=lowestCommonAncestor(root->right,p,q);
38+
39+
if(lefty!=NULL && righty!=NULL)
40+
return root;
41+
else{
42+
if(lefty!=NULL)
43+
return lefty;
44+
return righty;
45+
}
46+
//return root;
47+
}
48+
};

0 commit comments

Comments
 (0)