Tuesday, December 8, 2009

Given the value of two nodes in a binary search tree, find the lowest (nearest) common ancestor. You may assume that both values already exist in the tree.

Given the value of two nodes in a binary search tree, find the lowest (nearest) common ancestor. You may assume that both values already exist in the tree.

Node findLowestCommonAncestor( Node root, int value1, int value2 )
{
    while( root != null )
    {
        int value = root.getValue();
        if( value > value1 && value > value2 )
        {
            root = root.getLeft();
        }
        else if( value < value1 && value < value2 )
        {
            root = root.getRight();
        }
        else
        {
            return root;
        }
    }
   return null; // only if empty tree
}
// Overload it to handle nodes as well
Node findLowestCommonAncestor( Node root, Node child1, Node child2 )
{
    if( root == null || child1 == null || child2 == null )
    {
        return null;
    }
    return findLowestCommonAncestor( root, child1.getValue(), child2.getValue() );
}

No comments:

Post a Comment