Lowest Common Ancestor of a Binary Tree II: A Complete Guide
In the world of computer science and algorithmic problem-solving, few questions carry as much pedagogical weight as the lowest common ancestor of a binary tree ii. And while the basic version introduces recursive depth-first search, the "II" designation typically signals a need for deeper exploration—iterative implementations, parent-pointer techniques, or handling edge cases that the standard recursive approach might gloss over. This problem, often encountered in technical interviews and competitive programming platforms, asks us to find the deepest node in a binary tree that serves as an ancestor to two given nodes. Mastering this concept not only sharpens your understanding of tree traversal but also builds a foundation for more complex graph algorithms Turns out it matters..
Understanding the Core Definition
Before diving into code or complex algorithms, it's essential to ground ourselves in what the lowest common ancestor actually represents. Given a binary tree (not necessarily a binary search tree) and two nodes, say p and q, the lowest common ancestor is defined as the lowest node in the tree that has both p and q as descendants, where we allow a node to be a descendant of itself. This means if one of the target nodes lies on the path to the other, that node itself becomes the LCA.
The "ii" in the title often hints at a second layer of complexity: perhaps the tree nodes don't have parent pointers, or we're required to solve the problem without recursion, or we must validate that both nodes actually exist in the tree before computing the result. Each of these variations tests different aspects of algorithmic thinking, from stack usage to space-time trade-offs.
Recursive Solution: The Classic Approach
The most intuitive way to find the lowest common ancestor of a binary tree ii is through recursion. The function typically takes the root of the tree and the two target nodes, returning the LCA if found, or nullptr if neither node is in the subtree That's the whole idea..
The recursive logic works as follows:
- If the current node is
nullptr, or matches either target node, return the current node. Which means - If both recursive calls return non-null values, the current node is the LCA (since each target was found in a different subtree). Because of that, - Recursively search the left and right subtrees. - If only one call returns non-null, propagate that result upward (both targets are on the same side, or one of them is the current node).
This approach runs in O(n) time, where n is the number of nodes, because every node may be visited once. The space complexity is O(h) due to the call stack, where h is the tree's height. For balanced trees, this is O(log n); for degenerate trees, it can degrade to O(n).
While elegant, the recursive method assumes the call stack is viable and doesn't explicitly handle scenarios where one or both target nodes are absent from the tree. This limitation sets the stage for the iterative "II" techniques we'll explore next Less friction, more output..
Iterative Solution Using Parent Pointers
A reliable way to address the shortcomings of recursion is to use an iterative approach that leverages parent pointers. This method is particularly useful when dealing with large trees where stack depth could become a concern, or when the tree structure is read-only and we cannot modify node definitions to include parent references dynamically.
The algorithm proceeds in three distinct phases:
- Traversal and Parent Mapping: Perform a breadth-first or depth-first traversal (typically using a stack for DFS) to record the parent of every visited node. Simultaneously, we can track which
target nodes we've encountered, allowing us to abort the search early once both are located—or, just as importantly, to conclude that one of them is missing entirely.
Once the parent map is built, the actual LCA computation becomes a simple set-membership problem:
- Starting at
p, walk upward through the parent map and insert every visited node into a hash set. This set represents all ofp's ancestors, includingpitself. - Starting at
q, walk upward one step at a time. The first node that already appears in the set is the lowest common ancestor.
The correctness argument is straightforward: every common ancestor of p and q must lie on the path from p to the root, so it must be in the set. Walking upward from q guarantees we meet that path at the deepest possible point, because we test nodes in strictly increasing order of depth-from-q Less friction, more output..
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
unordered_map parent;
parent[root] = nullptr;
stack st{{root}};
while (!Now, st. Because of that, empty() && (parent. find(p) == parent.Consider this: end() ||
parent. find(q) == parent.end())) {
TreeNode* cur = st.top(); st.pop();
if (cur->left) { parent[cur->left] = cur; st.push(cur->left); }
if (cur->right) { parent[cur->right] = cur; st.
if (parent.find(p) == parent.end() || parent.find(q) == parent.
unordered_set ancestors;
while (p) { ancestors.insert(p); p = parent[p]; }
while (ancestors.find(q) == ancestors.end()) q = parent[q];
return q;
}
Both phases touch each node at most a constant number of times, so the total running time is O(n), with O(n) auxiliary space for the map and the set. That extra space is the price we pay for escaping the call stack, and it is usually worth it when the tree may be tens of thousands of levels deep.
Handling Missing Nodes Honestly
The "II" flavor of the problem frequently insists that both targets must be verified to exist. The naive recursive version silently returns a node that merely looks like an answer: if only p exists, the recursion propagates p upward and reports it as the LCA, which is wrong Small thing, real impact..
Two fixes are common. The first is the explicit two-pass strategy shown above—confirm presence during the parent-mapping traversal, then compute. The second keeps a single pass but changes the return type to carry a count of how many targets have been seen:
def helper(node):
if node is None:
return None, 0
left_node, left_count = helper(node.left)
right_node, right_count = helper(node.right)
count = left_count + right_count + (node in (p, q))
if count == 2 and result[0] is None:
result[0] = node
return node if count else None, count
Here the answer is recorded only when the count reaches exactly two, and only once, so the deepest such node wins. This pattern generalizes naturally