Lowest Common Ancestor in a Binary Tree(###,cpp)

 

 

 Lowest Common Ancestor in a Binary Tree(###,cpp)


Given a Binary Tree with all unique values and two nodes value n1 and n2. The task is to find the lowest common ancestor of the given two nodes. We may assume that either both n1 and n2 are present in the tree or none of them is present. 

Example 1:

Input:
n1 = 2 , n2 =  3

     1
   /  \
  2    3
Output: 1
 
 

Example 2:

Input: n1 = 3 , n2 = 4         5        /       2     /  \    3   4 Output: 2
 

----------------------------------------------------------------------------------------------------------------------------

Node* lca(Node* root ,int n1 ,int n2 )
{
    if(root==NULL)
      return root;
     
   if(root->data==n1  || root->data==n2)
      return root;
     
   Node * l=lca(root->left,n1,n2);
   Node * r=lca(root->right,n1,n2);
   if(l==NULL && r==NULL)
      return NULL;
    else if(l!=NULL && r!=NULL)
       return root;
     
     
    else if(l!=NULL && r== NULL)
        return l;
    else
      return r;
     
      
}
 

Comments

Popular posts from this blog

Amazing Subarrays(cpp,interviewbit)

Symmetric Tree(leetcode,cpp):

sum of left leaves in a tree(leetcode).