Lowest Common Ancestor of a Binary Tree
Medium
Topics
You are given the root of a binary tree whose node values are all different, plus two values p and q that both appear in the tree. Return the value of their lowest common ancestor: the deepest node that has both of them in its subtree. A node counts as part of its own subtree, so if one value sits below the other, the upper one is the answer.
Unlike the search-tree version of this problem, the values follow no ordering, so you cannot tell which side to go down by comparing numbers.
Example 1
null marks a missing child.Input: root = [8,4,12,2,6,10,14], p = 2, q = 6 Output: 4
Example 2
Input: root = [8,4,12,2,6,10,14], p = 6, q = 14 Output: 8
Example 3
Input: root = [1,7,null,3], p = 7, q = 3 Output: 7 Explanation: 3 is inside the subtree of 7.
Constraints
- 2 <= number of nodes <= 10^5
- -10^9 <= Node.val <= 10^9
- All values are distinct.
- p != q, and both exist in the tree.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Ask each subtree a single question: does it contain p, q, or neither? The first node, walking upwards, where the answer arrives from two different directions (left and right, or itself and one child) is where the two paths to p and q meet.
Approach
- Recurse post-order. An empty subtree reports nothing.
- If the current node is p or q, report the current node.
- Otherwise ask both children. If both report something, the current node is the meeting point: report it.
- If only one child reports, pass its report upward unchanged.
- The report that reaches the root is the answer.
Dry Run
tree 8 4 12 2 6 10 14
8
/ \
4 12
/ \ / \
2 6 10 14
Without an ordering to exploit, every node asks its two subtrees "did you find
either target?" and the answers come back up:
p = 2, q = 6
node 2 is a target, return it up
node 6 is a target, return it up
node 4 received a hit from BOTH sides -> node 4 is the LCA
node 10 passes up nothing
node 14 passes up nothing
node 12 passes up nothing
node 8 passes up the 4 it got from the left
answer 4
p = 6, q = 14
node 4 passes up the 6
node 12 passes up the 14
node 8 received a hit from both sides -> answer 8
The return value carries two different meanings, and that overloading is the
trick: "the LCA" once found, and "one target I saw down here" before then. Both
travel up the same channel, and the node that receives a non-null from each side
is the first one that can see both -- which is the definition of lowest common
ancestor.
Note what happens at node 4 in the second case. It found the 6 and returns it
unchanged, NOT itself, because one hit is not enough. Only `left and right`
promotes a node to the answer.
The walk stops at a target without looking below it, which is correct only because
the problem guarantees both nodes exist. If q were absent, p would be reported as
the ancestor of a pair that has none.Complexity
- Time — O(n): every node is visited once.
- Space — O(h): the recursion stack, up to the tree height; use an explicit stack for very deep trees.
Common Pitfalls
- Stopping at p without looking below it is correct only because q is guaranteed to exist: if q were missing, p would be wrongly reported.
- Recursion on a 10^5-node chain can overflow the default stack in Python and Java; an iterative parent-map walk avoids it.
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
if node.val == p or node.val == q:
return node
left = walk(node.left)
right = walk(node.right)
if left and right:
return node
return left or right
found = walk(root)
return found.val if found 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;
TreeNode found = walk(root);
return found != null ? found.val : -1;
}
private int targetP, targetQ;
private TreeNode walk(TreeNode node) {
if (node == null) return null;
if (node.val == targetP || node.val == targetQ) return node;
TreeNode left = walk(node.left);
TreeNode right = walk(node.right);
if (left != null && right != null) return node;
return left != null ? left : right;
}
}#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) {
function<TreeNode*(TreeNode*)> walk = [&](TreeNode* node) -> TreeNode* {
if (!node) return nullptr;
if (node->val == p || node->val == q) return node;
TreeNode* left = walk(node->left);
TreeNode* right = walk(node->right);
if (left && right) return node;
return left ? left : right;
};
TreeNode* found = walk(root);
return found ? found->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;
if (node.val === p || node.val === q) return node;
const left = walk(node.left), right = walk(node.right);
if (left && right) return node;
return left || right;
};
const found = walk(root);
return found ? found.val : -1;
};