Lowest Common Ancestor of a Binary Tree
MediumTop Interview 150 TreesAirwallexWixMetaAtlassianProblem
Given a binary tree and two of its nodes, p and q, return their lowest common
ancestor: the lowest node that has both p and q in its subtree. A node counts as part of
its own subtree, so p may be the answer.
The tree is given in level order, with null for a missing child. The values are all different,
and p and q are given by their values. The answer is the value of the node returned.
Constraints
- 2 ≤ number of nodes ≤ 100000
- All Node.val are unique
- p ≠ q, and both are in the tree
Examples: pick one to animate
Solutions
Time: Each node is visited at most once, with constant work per node.
Space: The recursion is as deep as the tree is tall, h. That is log n for a balanced tree and n for a chain.
There is no ordering to lean on, so search both sides. A call returns none if neither target is below, returns the target if it reaches one, and otherwise returns whatever its children found. If both children return something, the two targets are on different sides, so this node is the answer. If only one does, pass that result up: it is either the single target found, or the answer already found below.