John Roberts
John Roberts

Reputation: 5966

Find Lowest Common Ancestor Code Explanation

I'm looking at the following code from Programming Interviews Exposed, and I can't seem to understand how exactly it works. Won't this method always return null?

// 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() );
}

Upvotes: 0

Views: 171

Answers (1)

From the code snippet, we don't really know what getValue returns. So if there are other overloaded versions of findLowestCommonAncestor, and getValue returns something other than Node, then the call to findLowestCommonAncestor in your snippet is not recursively calling itself.

Upvotes: 2

Related Questions