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;
}