Sunday, September 24, 2017

236. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4
For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Solution:
This problem is the extension of 

235. Lowest Common Ancestor of a Binary Search Tree


This one is a genera tree, which doesn't allow us to use value to determine a node's parent. 
But we can use recursion to get lowest common ancestor.
For base case, if root==null || root == p || root == q, return root. 
Then we recursively use the function to get left child's lowest common ancestor for p and q. Let's define it as leftCommon. Similarly we can get rightCommon.
Obviously if leftCommon is null we return rightCommon, and if rightCommon is null we return leftCommon.
For example, p is node 6 while q is node 7. LeftCommon should be 5, while rightCommon is null.
The other situation is both leftCommon and rightCommon are not null, which means leftCommon is p while rightCommon is q or vice versa. In this case we should return root. Eg p=6, q =8. leftCommon is 6 and rightCommon is 8, so we return 3. 

   public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {  
     if(root==null || root==p || root==q) return root;  
     TreeNode leftCommon=lowestCommonAncestor(root.left,p,q);  
     TreeNode rightCommon=lowestCommonAncestor(root.right,p,q);  
     if(leftCommon==null) return rightCommon;  
     if(rightCommon==null) return leftCommon;  
     return root;  
   }  

No comments:

Post a Comment