Wednesday, February 25, 2009

Least Common Parent of two nodes in a Binary Search Tree

Write the code to find out the least common ancestor of two nodes (a and b) in a binary search tree. Complexity o(logn)

Logic:
Since it is a binary search tree. We can check at every node whether the values of a and b lie to the left or right. In case they lie to the left, we can move to the left recursively. else we can move to the right recursively. When u get a node such that the value of node lies between a and b return.

// check always send the a node as the one which has a lower value as compared to the node b value

struct node * leastCommonAncestor(struct node * root, struct node * a, struct node * b)
{
if( root == NULL)
return NULL;

if( a->data <= root->data && b->data > root->data)
return (root);

else if( a->data <>data && b->data <>data)
return(leastCommonAncestor(node->left, a, b));

else if( a->data > root->data && b->data > root->data)
return(leastCommonAncestor(node->right, a, b));

}

No comments:

Post a Comment