Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes
v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
For example, the lowest common ancestor (LCA) of nodes 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a
node can be a descendant of itself according to the LCA definition.
求最近的公共祖先,很显然,对于二叉搜索树来说,当两个节点的值都比root小的时候,lca应该在root左节点这一侧, 都比root值大的时候都在右节点这一侧,否则root
就是lca,代码见下所示:
/**
* 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:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(max(p->val, q->val) < root->val)
lowestCommonAncestor(root->left, p, q);
else if(min(p->val, q->val) > root->val)
lowestCommonAncestor(root->right,p ,q);
else
return root;
}
};
而对于非二叉搜索树来说,做法一般是先分别查找到到P以及Q的路线,然后对比路线,找出LCA,代码如下:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL || p == NULL || q == NULL)
return NULL;
vector<TreeNode *>pathP;
vector<TreeNode *>pathQ;
pathP.push_back(root);
pathQ.push_back(root);
getPath(root, p, pathP);
getPath(root, q, pathQ);
TreeNode * lca = NULL;
for(int i = ; i < pathP.size() && i < pathQ.size(); ++i){
if(pathP[i] == pathQ[i]) //检查lca
lca = pathP[i];
else break;
}
return lca;
} bool getPath(TreeNode * root, TreeNode * target, vector<TreeNode * > & path)
{
if(root == target)
return true;
if(root->left){
path.push_back(root->left);
if(getPath(root->left, target, path)) return true;
path.pop_back();
}
if(root->right){
path.push_back(root->right);
if(getPath(root->right, target, path)) return true;
path.pop_back();
}
return false;
}
};
java版本的如下所示:
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(Math.max(p.val, q.val) < root.val){
return lowestCommonAncestor(root.left, p, q);
}else if(Math.min(p.val, q.val) > root.val){
return lowestCommonAncestor(root.right, p, q);
}else{
return root;
}
}
}