Saturday, February 8, 2014

Distance between two nodes of binary tree





static int distanceOfTwoNodes(Node root, Node x, Node y)
{
if(root == null) return 0;

int l = distanceOfTwoNodes(root.left, x, y);
int r = distanceOfTwoNodes(root.right, x, y);

if(l != 0 || r != 0) return (l+r+1);
if(root.data == x.data || root.data == y.data) return 1;


return 0;
}

No comments:

Post a Comment