Lowest Common Ancestor Binary Tree

Lowest Common Ancestor Binary Tree

Algorithm:
  • This algorithm assumes that both node present in tree
  • Traverse tree in PostOrder fashion
  • If node is null then
    • return null
  • If node is equal to n1 or n2
    • return node
  • If left and right both are not null then
    • return node and its a LCA
  • If at most of node is null then
    • return not null node.

Video

Latest Source Code:
Github: BinaryTreeLowestCommonAncestor.java


Output:

       3               
      / \       
     /   \      
    /     \     
   /       \    
   6       8       
  / \       \   
 /   \       \  
 2   11       13   
    / \     /   
    9 5     7   
                                
LCA of 2 and 5 :6
LCA of 9 and 13 :3
LCA of 8 and 7 :8
Author: Hrishikesh Mishra