19 Responses

I have not read the paper yet (thank you Cosmin for posting it), but the posts here are all incomplete. Here are the points to consider and test your proposed algorithm on:
1. Your routine should return null if one or both nodes you are looking for are not in the tree. All posted algorithms fail this test if one of the two values are present and the other is missing.
2. Your routine should work if one of the sought nodes is the ancestor of the other. Again, both proposed solutions in the text fail this, since the moment you find one of the sought nodes the algorithm returns and the children of that node are never examined.
3. Your routine should work if the two sought values are the same.

It is a binary search tree. So given two nodes say x and y. Assume x x and < y.

The algorithm: Starting from root, if it is greater than both x and y, then we check the left child of the root. If the root is less than both x and y, then we check the right child of the root. This check will keep going until find a node z (x<z<y).

Why is the official answer an algorithm that runs in time linear in the size of the tree when there are algorithms that use the fact that the tree is a binary search tree to find the answer in time linear in the depth of the tree?

pass 1) start from node n1 and n2, for each go up to the root, to know how deep in tree we are, record height as h1, and h2.
pass 2) restart from n1 and n2. for deeper node (say n2, with h2 depth), perform h2-h1 jumps to the parent. Then start synchronously travering up by one in n1 and n2, and stop when you land in some step you have same node on both sides (which will be eventually root).