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,则返回 root 即可
递归
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(p->val < root->val && q->val < root->val)
return lowestCommonAncestor(root->left, p, q);
if(p->val > root->val && q->val > root->val)
return lowestCommonAncestor(root->right, p, q);
//在左右两边,或者某一个等于 root
return root;
}
迭代
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while(true){
if((root->val - p->val)*(root->val - q->val) <= 0) return root;
else root = (root->val - p->val > 0? root->left : root->right);
}
}
写一个检查函数即可
/*
* check whether the node n is in the tree
*/
private static boolean covers(Node rootNode, Node n) {
if(rootNode == null) return false;
if(rootNode == n) return true;
return covers(rootNode.leftChild, n) || covers(rootNode.rightChild, n);
}
/*
* get the first common ancestor of node p and node q
*/
public static Node commonAncestor(Node rootNode, Node p, Node q) {
if (covers(rootNode.leftChild, p) && covers(rootNode.leftChild, q))
return commonAncestor(rootNode.leftChild, p, q);
if (covers(rootNode.rightChild, p) && covers(rootNode.rightChild, q))
return commonAncestor(rootNode.rightChild, p, q);
return rootNode;
}