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?