-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create Lowest Common Ancestor in binary tree.cpp
- Loading branch information
1 parent
3df79f1
commit f3cefed
Showing
1 changed file
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |