Lowest Common Ancestor of a Binary Tree II
Medium
Topics
Given the root of a binary tree with distinct node values, and two values p and q, return the value of their lowest common ancestor.
The lowest common ancestor of p and q is the deepest node that has both of them as descendants, where a node counts as a descendant of itself.
Unlike the classic version of this problem, p or q may be absent from the tree. If either one is missing, return -1.
Example 1
3, and no node below it holds both, so the answer is 3.null marks a missing child.Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 Output: 3 Explanation: The two values sit in different subtrees of the root, so the root is the lowest node containing both.
Example 2
5 contains both, and nothing deeper does, giving 5.Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 Output: 5 Explanation: Node 4 is a descendant of 5, and a node is its own descendant, so 5 is the answer.
Example 3
10 is nowhere in this tree. Finding 5 is not enough on its own — so there is no answer and the result is -1. This is the whole difference from the classic version, where both values are promised to exist.Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 10 Output: -1 Explanation: There is no node with value 10, so no common ancestor exists.
Constraints
- 1 <= number of nodes <= 10^4
- -10^9 <= Node.val <= 10^9
- All Node.val are unique
- p != q
Editorial — intuition, approach, complexity and pitfalls
Intuition
The classic version is allowed to stop the moment it finds either target, because both are guaranteed present. Here that shortcut is exactly what breaks: if q is missing, finding p and returning it reports p as the answer, which is wrong — there is no answer at all.
So presence has to be established before any ancestor is reported. The cheap way to do that is to make the traversal count what it finds rather than stop at the first hit: visit the whole tree, and have each node report back both the candidate ancestor beneath it and how many of the two targets live down there.
A node is the lowest common ancestor exactly when the subtree rooted at it contains both targets and no child’s subtree does. Tracking the count gives that test directly, and it also answers the absence question for free — if the count at the root is less than two, one of the targets is not in the tree.
Approach
- Recurse over every node, returning two things: the best candidate found in this subtree, and how many of
{p, q}it contains. - At a node, recurse into both children first, then add one if the node’s own value is
porq. - If the total count for this node’s subtree is 2 and neither child already reported a candidate, this node is the lowest common ancestor — report it.
- Otherwise pass up whichever child’s candidate exists, along with the count.
- At the top, return the candidate only if the root’s count reached 2; otherwise return
-1.
Walkthrough
root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
subtree rooted at contains p,q candidate
6 0 -
7 0 -
4 1 (q) -
2 1 -
5 2 (p and q) 5 <- both found, no child had a candidate
1 0 -
3 2 5 (passed up unchanged)
root count is 2, so the answer is 5
With q = 10 instead, the root count is 1 and the answer is -1,
even though node 5 was found along the way.Complexity
- Time — O(n): every node is visited exactly once. The whole tree must be visited, since stopping early is what makes the absent case unanswerable.
- Space — O(h): the recursion stack, where h is the tree height.
Common Pitfalls
- Reusing the classic solution unchanged. It returns a node whenever it finds one target, so a missing
qyieldspinstead of-1. - Checking presence with two separate searches and then running the classic version. That works but walks the tree three times; one counting pass does the same job.
- Forgetting that a node is its own descendant. Example 2 answers 5, not 2, because the ancestor relation includes the node itself.
- Reporting the first node whose count reaches 2 while unwinding without checking the children. The deepest such node is wanted, so a child’s candidate always wins.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def lowestCommonAncestor(self, root, p, q):
def walk(node):
if not node:
return None, 0
left, left_n = walk(node.left)
right, right_n = walk(node.right)
found = left_n + right_n + (1 if node.val in (p, q) else 0)
if left:
return left, found
if right:
return right, found
if found == 2:
return node, found
return None, found
node, found = walk(root)
return node.val if found == 2 and node else -1import java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int lowestCommonAncestor(TreeNode root, int p, int q) {
targetP = p;
targetQ = q;
best = null;
int found = walk(root);
return (found == 2 && best != null) ? best.val : -1;
}
private int targetP, targetQ;
private TreeNode best;
private int walk(TreeNode node) {
if (node == null) return 0;
TreeNode before = best;
int left = walk(node.left);
boolean leftFound = best != before;
before = best;
int right = walk(node.right);
boolean rightFound = best != before;
int here = left + right + ((node.val == targetP || node.val == targetQ) ? 1 : 0);
if (!leftFound && !rightFound && here == 2) best = node;
return here;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int lowestCommonAncestor(TreeNode* root, int p, int q) {
int found = 0;
function<pair<TreeNode*, int>(TreeNode*)> walk = [&](TreeNode* node) -> pair<TreeNode*, int> {
if (!node) return {
nullptr, 0
};
pair<TreeNode*, int> L = walk(node->left), R = walk(node->right);
int here = L.second + R.second + ((node->val == p || node->val == q) ? 1 : 0);
if (L.first) return {
L.first, here
};
if (R.first) return {
R.first, here
};
if (here == 2) return {
node, here
};
return {
nullptr, here
};
};
pair<TreeNode*, int> res = walk(root);
found = res.second;
return (found == 2 && res.first) ? res.first->val : -1;
}
};/** Tree node shape: { val, left, right } */ /**
* @param {TreeNode} root
* @param {number} p
* @param {number} q
* @return {number}
*/ var lowestCommonAncestor = function(root, p, q) {
const walk = (node) => {
if (!node) return [null, 0];
const L = walk(node.left), R = walk(node.right);
const found = L[1] + R[1] + ((node.val === p || node.val === q) ? 1 : 0);
if (L[0]) return [L[0], found];
if (R[0]) return [R[0], found];
if (found === 2) return [node, found];
return [null, found];
};
const res = walk(root);
return (res[1] === 2 && res[0]) ? res[0].val : -1;
};