问题: 给定一个二叉查找树(BST),找到给定两个节点的最小公共祖先。
_6_
/ \
2 8
/ \ / \
0 4 7 9
/ \
3 5
例如节点2和8的最小公共祖先是6。2和4的最小公共祖先是2,因为一个节点可以看作是它本身的子节点。
代码:
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {//二分查找树,左节点小于根节点,右节点大于根节点
if((p.val<=root.val&&q.val>=root.val)||(p.val>=root.val&&q.val<=root.val))//如果p,q在根节点的左右两边
return root;
else
{
if(p.val<root.val&&q.val<root.val)//都在一边,递归
return lowestCommonAncestor(root.left,p,q);
else
return lowestCommonAncestor(root.right,p,q);
}
}
}