Lowest Common Ancestor of a Binary Tree
The problem
Section titled “The problem”You get the root of a binary tree and two nodes p and q that are both in the tree.
Return their lowest common ancestor: the deepest node that has both p and q in its
subtree. A node counts as its own descendant.
root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 1 -> 3root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 4 -> 5In the second case 5 is an ancestor of 4, so 5 is the answer.
Key insight
Section titled “Key insight”This is not a search tree, so there is no ordering to steer by. Instead let each call
answer: “what did I find in this subtree?” Return p or q if you hit one, otherwise
return whatever the children found.
At any node there are three outcomes. If both children return something non-null, p
is on one side and q on the other, so this node is the split point and the answer. If only
one child returns something, pass it up: it is either a target or an answer already found
below. If neither does, return null.
Stopping at the first target is safe. If the other target is below it, this target is the answer. If not, the other one is found elsewhere and the split happens higher up.
Show solutionHide solution
def lowest_common_ancestor(root: TreeNode | None, p: TreeNode, q: TreeNode) -> TreeNode | None: if root is None or root is p or root is q: return root # hit a target (or ran off the tree): report it upward left = lowest_common_ancestor(root.left, p, q) right = lowest_common_ancestor(root.right, p, q) if left and right: return root # one target on each side: this node is the split point return left or right # both in one subtree (or neither): pass that result upexport function lowestCommonAncestor(root: TreeNode | null, p: TreeNode, q: TreeNode): TreeNode | null { if (root === null || root === p || root === q) return root; // hit a target (or ran off the tree): report it upward const left = lowestCommonAncestor(root.left, p, q); const right = lowestCommonAncestor(root.right, p, q); if (left && right) return root; // one target on each side: this node is the split point return left ?? right; // both in one subtree (or neither): pass that result up}class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) return root; // hit a target (or ran off the tree): report it upward TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left != null && right != null) return root; // one target on each side: this node is the split point return left != null ? left : right; // both in one subtree (or neither): pass that result up }}Complexity
Section titled “Complexity”- Time: O(n) — in the worst case every node is visited once.
- Space: O(h) — recursion stack depth is the tree height
h: O(log n) balanced, O(n) skewed.
Watch out for
Section titled “Watch out for”- Compare nodes, not values. The inputs are node references, so test identity
(
root is p). Tree values need not be unique, so comparing values can match the wrong node. - Don’t keep searching below a target. Returning as soon as you hit
porqis correct and is what handles the “one is the ancestor of the other” case. - The solution assumes both nodes exist. If one might be missing, you need to count how many targets were actually found before trusting the result.
Variations
Section titled “Variations”Lowest Common Ancestor of a Binary Search Tree (LeetCode 235)
Section titled “Lowest Common Ancestor of a Binary Search Tree (LeetCode 235)”Same question on a BST. The trick: use the ordering. If both values are smaller than the current node go left; if both are larger go right; otherwise this node splits them and is the answer. O(h) time, and iterative with O(1) space.
Lowest Common Ancestor of Deepest Leaves (LeetCode 1123)
Section titled “Lowest Common Ancestor of Deepest Leaves (LeetCode 1123)”Return the LCA of all the deepest leaves. The trick: each call returns
(depth, lca). If both children have the same depth, the node itself is the LCA;
otherwise take the deeper child’s result.
Binary Tree Maximum Path Sum (LeetCode 124)
Section titled “Binary Tree Maximum Path Sum (LeetCode 124)”A different problem with the same shape. The trick: each call returns the best downward path from its node, while a global answer tracks the best path that bends at it.