Google Interview Question

Find the lowest common ancestor for BST

Interview Answers

Anonymous

Jan 29, 2010

In BST you use the ordering property of BST: http://rmandvikar.blogspot.com/2008/08/lowest-common-ancestor-lca-in-binary.html

Anonymous

Mar 2, 2010

The lowest common ancestor will be between the two values, so perform a dfs until you reach a node that is between the two values.

Anonymous

Apr 25, 2010

We note that the lowest common ancestor must have a value between the 2 values you are given. Any other ancestors higher than that will have a number that is either greater or smaller than _both_ values. Hence the problem is simplified a lot. We can now simply traverse from the root, as if we are searching for the smallest of the 2 numbers. For each traversal, check whether the number is between the 2 values. If it is, return that node.

Anonymous

Jan 14, 2010

One solution is traversing the BST from top to bottom and for every node, you check its children. Then you recursively go down the chain until you reach the leaf.