Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Sunday, August 6, 2017

Lowest Common Ancestor in a Binary Tree


Explanation:

Here we will check when data is equal to either n1 or n2 return node , else recur for left & right , if left and right both points are not null it means that root have n1 , n2 for different subtree (LEFT /RIGHT).

check if one of the point is null then return the value which is not null.


Solution:

/* A Binary Tree node
class Node
{
    int data;
    Node left, right;
    Node(int item)
    {
        data = item;
        left = right = null;
    }
}*/
class hackerranksolutionc
{
Node LCA(Node root, int n1,int n2)
{
if(root==null)
return null;
if(root.data==n1 || root.data==n2)
return root;
Node left=LCA(root.left,n1,n2);
Node right= LCA(root.right,n1,n2);
if(left!=null && right!=null)
return root;
return (left!=null)?left:right;
}
}

0 Comments:

Post a Comment

Stats