Given a binary tree, find the lowest common ancestor of two given nodes in the tree.
_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4Amazon Interview Question
Key to solve: Bottom-up recursion
We traverse from the bottom, and once we reach a node which matches one of the two nodes,
we pass it up to its parent.
There are 3 cases
If yes, then the parent must be the LCA and we pass its parent up to the root.
If not, we pass the lower node which contains either one of the
two nodes (if the left or right subtree contains either p or q), or
NULL (if both the left and right subtree does not contain either p or q) up.
public TreeNode LCATree(TreeNode root,TreeNode p,TreeNode q){
//base case
if(root==null) return null;
//
if(root==p || root==q) return root;
TreeNode l=LCATree(root.left,p,q);
TreeNode r=LCATree(root.right,p,q);
//p and q on both branch
if(l!=null && r!=null) return root;
//either one of p,q is on one side
return l!=null ? l : r;
}