class TreeNode {
TreeNode parent;
TreeNode left;
TreeNode right;
// other data fields omitted - not relevant
}
You are given two nodes p, and q, how do you find the lowest common ancestor? (Assume they both belong in a very large tree)
You do NOT have reference to the root of the tree.
What is the most efficient way to do this? So far, the only idea I have was to
(1) pick a node p (doesn't matter which)
(2) search left sub tree of p, if see q, return p
(3) else search right sub tree of p, if see q, return p
(4) else go one level to parent and search the sub-tree that doesn't contain p, if found q, return parent
(5) else, go up one level again, repeat (4) (search the sub tree that doesnt contain this parent)
This seems extremely inefficient. Any better algorithm?
Do you have extreme restrictions on the amount of RAM you're allowed to use? If not, I'd propose something like this:
The intuitive idea is as follows. We start at both nodes at the same time. In every iteration of the loop, we take one step up from both of the nodes. Whenever we see a node, we put it in our map (which should have O(1) insertion and retrievals / checking if it's already in there). When we encounter a node that we've already put in the map, that must be our solution.
This code should never run for more than
max(d_p, d_q)iterations, whered_pandd_qdenote the depth levels in the tree thatpandqare at, respectively. This will especially be a large advantage if both nodes happen to be rather close to the root. It also means that the code even works for an infinite tree (whereas your solution would get stuck in an infinite loop).