Lowest Common Ancestor of a Binary Search Tree
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null)
return null;
if(root == q)
return q;
if(root == p)
return p;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left != null && right != null)
return root;
if(left != null)
return left;
else
return right;
}Last updated