Lowest Common Ancestor of a Binary Search Tree
MediumNeetCode 150 TreesXProblem
Given a binary search 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. All values are 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: It moves down one path, one level per step, so at most h steps, where h is the height.
Space: Only the cur pointer is kept. There is no recursion or stack.
In a search tree, if both targets are smaller than a node they are both in its left subtree, and if both are larger they are both in its right subtree. So start at the root and move toward them. The first node where they are not both on the same side is the lowest common ancestor: the paths split there, or that node is one of them.