topic
Given a binary tree, find the nearest common ancestor of two specified nodes in the tree.
The definition of the nearest common ancestor in Baidu Encyclopedia: "For T
two nodes u
, v
, of a rooted tree, the nearest common ancestor represents a node x
that satisfies x
yes u
, v
and the depth of the ancestor x
is as large as possible." (A node can also be itself Ancestor of )
For example, node 5
and node 1
's nearest common ancestor is node 3
; node 5
and node 4
's nearest common ancestor is node 5
, because by definition, a node can be its own ancestor.
answer
This question should be a common interview question. You can consider directly using two arrays to record the paths of u
and respectively v
, and then traverse the two paths to find the common ancestor
code
/**
* 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:
bool getAncestor(TreeNode* root,TreeNode *p,vector<TreeNode*> &vec){
if(root==NULL) return false;
if(root==p){
vec.push_back(root);
return true;
}
if(getAncestor(root->left,p,vec)||getAncestor(root->right,p,vec)){
vec.push_back(root);
return true;
}
return false;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
vector<TreeNode*> vp,vq;
getAncestor(root,p,vp);
getAncestor(root,q,vq);
int n=vp.size(),m=vq.size();
while(n>0&&m>0&&vp[n-1]==vq[m-1]){
n--;
m--;
}
return vp[n];
}
};