Lowest Common Ancestor of a Binary Tree
Problem
Given the root of a binary tree and two nodes p and q, return their lowest common ancestor (LCA), defined as the lowest node in the tree that has both p and q as descendants (a node can be a descendant of itself).
- The number of nodes in the tree is in the range [2, 10⁵]
- −10⁹ ≤ Node.val ≤ 10⁹
- All Node.val are unique
- p and q are different nodes and both exist in the tree
Example
root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 13Starting at the root (3), the algorithm recursively searches left and right subtrees for nodes p=5 and q=1. It finds p in the left subtree and q in the right subtree. Since both subtrees contain one of the nodes, the root (3) is the lowest common ancestor. The critical moment is when both left and right recursive calls return non-null, indicating the current node is the LCA.
Approach
Straightforward Solution
A brute-force approach might store parent pointers or paths from root to p and q, then compare paths to find the last common node. This requires extra space and multiple traversals.
Core Observation
The LCA of two nodes p and q is the lowest node in the tree whose left and right subtrees contain p and q respectively, or the node itself is p or q. This naturally suggests a recursive exploration of the tree to find p and q in subtrees.
Path to Optimal
The key insight is to use a single DFS traversal that returns the node if it matches p or q, or returns the LCA if found in subtrees. If both left and right recursive calls return non-null, the current node is the LCA. Otherwise, propagate the non-null return upwards. This approach avoids extra storage and finds the LCA in one pass.
Optimal Approach
Perform a recursive DFS starting at root. If the current node is null, return null. If it matches p or q, return the current node. Recursively search left and right subtrees. If both calls return non-null, return current node as LCA. If only one side returns non-null, propagate that upwards. This guarantees O(n) time and O(h) space, where h is tree height.
Time
O(n)
Each node is visited once during the DFS traversal, resulting in linear time proportional to the number of nodes.
Space
O(h)
The recursion stack uses space proportional to the height of the tree, which is O(h). This is auxiliary space excluding the input tree.
Pattern Spotlight
DFS (Postorder Traversal for State Propagation)
When searching for nodes in a tree to find a common ancestor, use DFS to propagate found nodes upward; the first node where both left and right subtrees report findings is the lowest common ancestor.
Solution
| 1 | class Solution: |
| 2 | def lowestCommonAncestor(self, root: "TreeNode", p: "TreeNode", q: "TreeNode") -> "TreeNode": |
| 3 | if not root: |
| 4 | return None |
| 5 | |
| 6 | if root == p or root == q: |
| 7 | return root |
| 8 | |
| 9 | left = self.lowestCommonAncestor(root.left, p, q) |
| 10 | right = self.lowestCommonAncestor(root.right, p, q) |
| 11 | |
| 12 | if left and right: |
| 13 | return root |
| 14 | |
| 15 | return left if left else right |
| 1 | import java.util.*; |
| 2 | |
| 3 | class Solution { |
| 4 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { |
| 5 | if (root == null) { |
| 6 | return null; |
| 7 | } |
| 8 | if (root == p || root == q) { |
| 9 | return root; |
| 10 | } |
| 11 | TreeNode left = lowestCommonAncestor(root.left, p, q); |
| 12 | TreeNode right = lowestCommonAncestor(root.right, p, q); |
| 13 | if (left != null && right != null) { |
| 14 | return root; |
| 15 | } |
| 16 | return left != null ? left : right; |
| 17 | } |
| 18 | } |
| 1 | #include <iostream> |
| 2 | using namespace std; |
| 3 | |
| 4 | class Solution { |
| 5 | public: |
| 6 | TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { |
| 7 | if (root == nullptr) { |
| 8 | return nullptr; |
| 9 | } |
| 10 | if (root == p || root == q) { |
| 11 | return root; |
| 12 | } |
| 13 | TreeNode* left = lowestCommonAncestor(root->left, p, q); |
| 14 | TreeNode* right = lowestCommonAncestor(root->right, p, q); |
| 15 | if (left != nullptr && right != nullptr) { |
| 16 | return root; |
| 17 | } |
| 18 | return left != nullptr ? left : right; |
| 19 | } |
| 20 | }; |
| 1 | var lowestCommonAncestor = function(root, p, q) { |
| 2 | if (root === null) { |
| 3 | return null; |
| 4 | } |
| 5 | if (root === p || root === q) { |
| 6 | return root; |
| 7 | } |
| 8 | const left = lowestCommonAncestor(root.left, p, q); |
| 9 | const right = lowestCommonAncestor(root.right, p, q); |
| 10 | if (left !== null && right !== null) { |
| 11 | return root; |
| 12 | } |
| 13 | return left !== null ? left : right; |
| 14 | }; |
Step-by-Step Solution
Return Null for Empty Subtrees to Signal Absence
| 3 | if not root: |
| 4 | return None |
Objective
To terminate recursion when reaching a null node, indicating p or q is not found in this path.
Key Insight
Returning null for empty subtrees is essential to signal that neither p nor q exists below this node. This base case prevents unnecessary traversal and allows the recursion to correctly propagate findings upward.
Interview Quick-Check
Core Logic
Returning null on a null node ensures the recursion correctly identifies absence of p and q in that subtree.
State & Boundaries
This base case is the stopping condition for the recursion.
Return Current Node When It Matches p or q
| 6 | if root == p or root == q: |
| 7 | return root |
Objective
To identify when the current node is one of the targets and propagate it upward as a potential ancestor.
Key Insight
If the current node is p or q, it must be returned immediately because it could be the LCA or a descendant of the LCA. This early return simplifies the logic by marking the presence of p or q in the current subtree.
Interview Quick-Check
Core Logic
Returning the current node when it matches p or q flags that one target has been found in this subtree.
Common Pitfalls & Bugs
Failing to return immediately when the current node matches p or q can cause incorrect ancestor detection.
Recursively Search Left and Right Subtrees for Targets
| 9 | left = self.lowestCommonAncestor(root.left, p, q) |
| 10 | right = self.lowestCommonAncestor(root.right, p, q) |
Objective
To explore both subtrees to find nodes p and q and gather information about their locations.
Key Insight
The recursive calls collect information about the presence of p and q in the left and right subtrees. This postorder traversal ensures that the algorithm only decides on the LCA after fully exploring both sides.
Interview Quick-Check
Core Logic
Recursive DFS calls gather presence information of p and q from both subtrees.
State & Boundaries
Both left and right calls must complete before deciding if current node is LCA.
Identify LCA When Both Subtrees Contain Targets
| 12 | if left and right: |
| 13 | return root |
Objective
To determine that the current node is the LCA if p and q are found in different subtrees.
Key Insight
If both left and right recursive calls return non-null, it means p and q are located in separate subtrees of the current node, making it the lowest node that connects them. Returning the current node here finalizes the LCA discovery.
Interview Quick-Check
Core Logic
The current node is the LCA if both left and right recursive calls return non-null, indicating p and q are split across subtrees.
Common Pitfalls & Bugs
Not checking both sides can cause missing the true LCA when p and q are in different branches.
Propagate Non-null Subtree Result Upwards
| 15 | return left if left else right |
Objective
To continue propagating the found target node or LCA upwards when only one subtree contains p or q.
Key Insight
If only one subtree returns a non-null node, it means both targets are either in that subtree or only one target has been found so far. Propagating this result upwards allows the recursion to eventually find the LCA higher in the tree or return the found node.
Interview Quick-Check
Core Logic
Returning the non-null subtree result ensures the presence of p or q is propagated correctly up the recursion stack.
State & Boundaries
If both sides are null, null is returned, indicating no targets found below.
Line Analysis
This solution has 5 Critical lines interviewers watch for.
if left and right:
Check if both left and right recursive calls found targets.
This condition detects the critical moment when p and q are found in separate subtrees, identifying the current node as the LCA.
return root
Return the current node as the LCA when both sides are non-null.
Returning the current node here finalizes the discovery of the lowest common ancestor, as it is the deepest node connecting p and q.
if root == p or root == q:
Check if the current node matches p or q.
Identifying p or q at the current node is critical to mark the presence of one of the targets in this subtree, enabling correct ancestor detection.
return root
Return the current node if it matches p or q.
Returning the matched node immediately flags its presence and allows the recursion to propagate this information upward.
return left if left else right
Return the non-null subtree result or None if both are null.
Propagating the found target or LCA upward ensures the recursion correctly bubbles up the relevant node, enabling the final answer to be returned at the root.
if not root:
Check if the current node is null.
This base case terminates recursion on empty branches, signaling that p or q cannot be found below this node.
return None
Return None for null nodes.
Returning None here propagates the absence of targets upward, allowing the algorithm to correctly identify where p and q are located.
left = self.lowestCommonAncestor(root.left, p, q)
Recursively search the left subtree for p or q.
Exploring the left subtree gathers information about the presence of p or q below the current node, essential for ancestor determination.
right = self.lowestCommonAncestor(root.right, p, q)
Recursively search the right subtree for p or q.
Exploring the right subtree complements the left search, ensuring both sides are checked for the targets.
Test Your Understanding
Why does returning the current node when both left and right recursive calls are non-null guarantee the lowest common ancestor?
Because it means p and q are found in different subtrees of the current node, so the current node is the deepest node that has both as descendants, fulfilling the definition of LCA.
Related Problems
DFS pattern
Don't just read it. Drill it.
Reconstruct Lowest Common Ancestor of a Binary Tree from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Lowest Common Ancestor of a Binary Tree drill