Given a binary tree, find the Lowest Common Ancestor (LCA) of two given nodes
The LCA is defined as the deepest node that has both
Output: 3
Explanation: LCA of nodes 5 and 1 is 3.
Output: 5
Explanation: LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself.
Constraints:
2 <= Number of nodes <= 105 - All node values are unique.
p != q ; bothp andq exist in the tree.
Contents
Solution — Recursive DFS Complexity Analysis
The key observations:
- If the current node is
null , returnnull . - If the current node is
p orq , return the current node immediately (it is the LCA if the other is a descendant, or we'll find the true LCA higher up). - Recurse into both subtrees. If both return non-null, the current node is the LCA (p and q are in different subtrees).
- If only one side returns non-null, propagate that result upward.
Trace for Example 1 (p=5, q=1):
- At node 3: recurse left (returns 5) and right (returns 1) → both non-null → return 3 ✓
- At node 5:
root == p → return 5 immediately - At node 1:
root == q → return 1 immediately
- Time: O(n) — visits each node at most once.
- Space: O(h) — recursion stack depth (O(log n) balanced, O(n) skewed).