您的位置:首页 > 其它

LCA in BST

2015-08-09 17:22 323 查看
题目:Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

思路:

两节点 p , q , 分多中情况考虑, 因为是BST, 如果 p < root , q > root ==> LCA = root

如果 p = Max(p , q ) < root == 》 LCA = LCA (root.left , p ,q) // 在左子树中求LCA

p = Max(p , q ) > root 同理

[code]public class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        int min = Math.min(p.val , q.val);
        int max = Math.max(p.val , q.val);

        while(root != null) {
            if(root.val > max) {
                return lowestCommonAncestor(root.left , p , q);
            } else if(root.val < max){
                if(root.val >= min)
                    return root;
                return lowestCommonAncestor(root.right, p , q);
            } else if(root.val == max) 
                return root;
        }
        return null;
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: