Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor of two given nodes in the BST.

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

Amazon Interview Question

Hint:
A top-down walk from the root of the tree is enough.

Lowest Common Ancestor Binary Search Tree:
    There are 3 condition:
    1.both nodes are on the left => move left
    2.both nodes are on the right => move right
    3. the nodes locate in separate branches    => return root

 //Solution_1
    public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode a, TreeNode b) {
        if (root == null || a == null || b == null) {
            return null;
        }
        if (Math.max(a.val, b.val) < root.val) {
            // both nodes are on the left
            return lowestCommonAncestor(root.left, a, b);
        } else
        if (Math.min(a.val, b.val) > root.val) {
            // both nodes are on the right
            return lowestCommonAncestor(root.right, a, b);
        } else {
            // the nodes locate on separate branches
            return root;
        }
    }
    //Solution_2
    public TreeNode LCABST(TreeNode root, TreeNode p,TreeNode q){
        //base case
        if(root==null) return null;
        if(p.val<root.val && q.val<root.val){
            LCABST(root.left,p,q);
        }
        if(p.val>root.val && q.val>root.val){
            LCABST(root.right,p,q);
        }
        return root;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值