Example 1
- Input
- root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
- Output
- 6
Basic split: the paths are [6,2] and [6,8]. Their last common node is 6; neither child subtree contains both targets. The output shows the returned node's value.
Given a binary search tree with two nodes p and q that both exist in it, return the deepest node that is an ancestor of both. A node counts as its own descendant.
Given the root of a binary search tree and two nodes p and q, return their lowest common ancestor.
The lowest common ancestor is the deepest node that has both p and q as descendants, where a node counts as a descendant of itself.
Both nodes are guaranteed to exist in the tree, they hold distinct values, and every value in the tree is unique.
2 <= number of nodes <= 10^5-10^9 <= Node.val <= 10^9p != q and both p and q exist in the treeBasic split: the paths are [6,2] and [6,8]. Their last common node is 6; neither child subtree contains both targets. The output shows the returned node's value.
Ancestor case: the paths are [6,2] and [6,2,4]. Node 2 counts as its own descendant, so it is the deepest common ancestor. Strict comparisons must stop when the current node equals a target.
Minimum-size edge case: the tree has only two nodes. The root 2 is both a target and the parent of 1, so return the existing root node.
Tricky deeper split with reversed target order: both targets are below 6 on its left, then above 2 on its right. At 4, 5 is larger and 3 is smaller. Return 4; the algorithm must work without assuming p has the smaller value.
A common ancestor lies on both root-to-target paths; the lowest one is the last node before those paths diverge. In Example 1, the paths to 2 and 8 share only 6. A BST adds a shortcut: if both target values are smaller than the current value, their shared path continues left; if both are larger, it continues right. At a split, or when the current node is a target, we have reached the answer. Return that original node reference, rather than its value or a new node.
Reveal Root To Node Paths: intuition, complexity, and code
The LCA is where two root-to-target routes stop sharing a prefix. A general tree needs path discovery and backtracking; BST ordering identifies the shared route using two value comparisons per node. Preserve the invariant that the chosen subtree contains both targets, then stop when no proper descendant can do so.