Monday, February 24, 2014

Find distance between two given keys of a Binary Tree




//  Instance variable distance to store the final distance b/w two nodes:

private static int distance = -1;

private static int distTwoNodesUtil(Node root, int n1, int n2){

                // Base condition:
                if(root == null) return 0;

int l = distTwoNodesUtil(root.left, n1, n2);
int r = distTwoNodesUtil(root.right, n1, n2);

                // if n1, n2 present at both side of  the root
if(l != 0 && r != 0)
{
distance = l+r;
}else if((l != 0 || r != 0) && ((root.data == n1) || (root.data == n2)))
{
distance = l+r;
}else if(l !=0 || r != 0)
{
return l+r+1;
}else if(root.data == n1 || root.data == n2)
{
return 1;
}

return 0;

}


static int distbwTwoNodes(Node root, int n1, int n2){
distTwoNodesUtil(root,n1,n2);
return distance;
}


References:

http://www.geeksforgeeks.org/find-distance-two-given-nodes/

No comments:

Post a Comment