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?
pone step at a time (and there is only one parent). At each step, recurse left and right completely, looking for theqnode. If found, return true otherwise return false. Along the way, as you touch each node, mark it as dirty so that you don't have to repeat the recursion at a higher level. - Tim Biegeleisen