Skip to content

Commit

Permalink
Merge pull request #289 from khushisaxena17/patch-1
Browse files Browse the repository at this point in the history
Create Lowest Common Ancestor in binary tree.cpp
  • Loading branch information
Ananyasingh2002 authored Oct 2, 2023
2 parents f770145 + f3cefed commit 3399943
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions Top_leetcode_problems/Lowest Common Ancestor.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* 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*> nodeToRootPath(TreeNode* root,int value){
if(root->val==value){
vector<TreeNode*>path;
path.push_back(root);
return path;
}
vector<TreeNode*>result;
if(root->left!=NULL){
result= nodeToRootPath(root->left,value);
if(result.size()>0){
result.push_back(root);
}
}
if(result.size()==0){
if(root->right!=NULL){
result=nodeToRootPath(root->right,value);
if(result.size()>0){
result.push_back(root);
}
}
}
return result;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
vector<TreeNode*>path1=nodeToRootPath(root,p->val);
vector<TreeNode*>path2=nodeToRootPath(root,q->val);
int i=path1.size()-1;
int j=path2.size()-1;
TreeNode* result=NULL;
while(i>=0 && j>=0){
if(path1[i]->val==path2[j]->val){
result=path1[i];
}
else{
break;
}
i--;
j--;
}
return result;
}
};

0 comments on commit 3399943

Please sign in to comment.