Lowest Common Ancestor of a Binary Tree III
Lowest Common Ancestor of a Binary Tree III is a medium trees & bst problem solved with the lca pattern.
The best approach, optimal (two pointers that switch paths), runs in O(h) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from ancestor set up.
Problem
You are given two nodes, p and q, of the same binary tree. You are not given the root. Instead, every node knows its parent:
class Node {
int val;
Node left;
Node right;
Node parent; // null for the root
}
Return their lowest common ancestor: the deepest node that has both p and q in its subtree. A node is part of its own subtree, so if p lies below q, the answer is q.
For the examples and tests, the tree is written in level order with null for missing children, and p and q are given by their values (all values are different). Your function receives the two nodes themselves, with their parent links already set, and returns the answer node.
Examples
Example 1
- Input
root = [10, 4, 15, 2, 7, null, 20, null, null, 5, 9], p = 5, q = 9- Output
7- Why
- Nodes 5 and 9 are the two children of node 7, so 7 is the deepest node that has both of them below it.
Example 2
- Input
root = [10, 4, 15, 2, 7, null, 20, null, null, 5, 9], p = 5, q = 20- Output
10- Why
- Going up from 5 visits 7, 4 and 10. Going up from 20 visits 15 and 10. The first node the two paths share is the root, 10.
Example 3
- Input
root = [10, 4, 15, 2, 7, null, 20, null, null, 5, 9], p = 7, q = 5- Output
7- Why
- Node 5 lies below node 7, and a node counts as its own ancestor, so the answer is 7 itself.
Constraints
- The tree has
2to10^5nodes. -10^9 <= Node.val <= 10^9- All values in the tree are different.
p != q, and bothpandqare nodes of the tree.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Ancestor set | O(h) | O(h) |
| Line up the depths | O(h) | O(1) |
| Optimal (two pointers that switch paths) | O(h) | O(1) |
1Ancestor set
O(h)Each walk follows at most h parent links, where h is the height of the tree.O(h)The set stores every ancestor of p, up to h + 1 nodes.Walk from p up to the root and put every node on the way into a hash set. Then walk up from q. The first node that is already in the set is an ancestor of both, and since we meet it from below, it is the lowest one.
- Start at p and follow parent links until null, adding each node to a set (p itself included).
- Start at q and follow parent links.
- Return the first node on q's path that the set contains.
- Both nodes are in the same tree, so the root at the latest is shared, and the loop always returns.
class Solution {
public Node lowestCommonAncestor(Node p, Node q) {
Set<Node> seen = new HashSet<>();
for (Node a = p; a != null; a = a.parent) seen.add(a);
for (Node b = q; b != null; b = b.parent) {
if (seen.contains(b)) return b;
}
return null;
}
}class Solution:
def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
seen = set()
a = p
while a is not None:
seen.add(a)
a = a.parent
b = q
while b is not None:
if b in seen:
return b
b = b.parent
return Noneclass Solution {
public:
Node* lowestCommonAncestor(Node* p, Node* q) {
unordered_set<Node*> seen;
for (Node* a = p; a != nullptr; a = a->parent) seen.insert(a);
for (Node* b = q; b != nullptr; b = b->parent) {
if (seen.count(b)) return b;
}
return nullptr;
}
};function lowestCommonAncestor(p, q) {
const seen = new Set();
for (let a = p; a !== null; a = a.parent) seen.add(a);
for (let b = q; b !== null; b = b.parent) {
if (seen.has(b)) return b;
}
return null;
}2Line up the depths
O(h)Two walks to measure the depths, then at most h more steps for each pointer.O(1)Only two pointers and two counters.Measure how far each node is from the root. Move the deeper one up until both are at the same depth. From there, step both up together; the first time they land on the same node, that node is the answer. No extra memory is needed.
- depth(x): count parent links from x until the root.
- While p is deeper than q, move p up one level; while q is deeper, move q up.
- Now both are at the same depth. While p != q, move both up one level.
- Return p (which now equals q).
class Solution {
public Node lowestCommonAncestor(Node p, Node q) {
int dp = depth(p), dq = depth(q);
while (dp > dq) {
p = p.parent;
dp--;
}
while (dq > dp) {
q = q.parent;
dq--;
}
while (p != q) {
p = p.parent;
q = q.parent;
}
return p;
}
private int depth(Node node) {
int d = 0;
while (node.parent != null) {
node = node.parent;
d++;
}
return d;
}
}class Solution:
def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
dp, dq = self.depth(p), self.depth(q)
while dp > dq:
p = p.parent
dp -= 1
while dq > dp:
q = q.parent
dq -= 1
while p is not q:
p = p.parent
q = q.parent
return p
def depth(self, node: 'Node') -> int:
d = 0
while node.parent is not None:
node = node.parent
d += 1
return dclass Solution {
public:
Node* lowestCommonAncestor(Node* p, Node* q) {
int dp = depth(p), dq = depth(q);
while (dp > dq) {
p = p->parent;
dp--;
}
while (dq > dp) {
q = q->parent;
dq--;
}
while (p != q) {
p = p->parent;
q = q->parent;
}
return p;
}
private:
int depth(Node* node) {
int d = 0;
while (node->parent != nullptr) {
node = node->parent;
d++;
}
return d;
}
};function lowestCommonAncestor(p, q) {
let dp = depth(p), dq = depth(q);
while (dp > dq) {
p = p.parent;
dp--;
}
while (dq > dp) {
q = q.parent;
dq--;
}
while (p !== q) {
p = p.parent;
q = q.parent;
}
return p;
}
function depth(node) {
let d = 0;
while (node.parent !== null) {
node = node.parent;
d++;
}
return d;
}3Optimal (two pointers that switch paths)
O(h)Each pointer walks at most both upward paths, which is at most 2h + 2 steps.O(1)Only the two pointers.Pointer a starts at p and pointer b at q, and both climb one level per step. When a falls off the top (null), it jumps to q; when b falls off, it jumps to p. Each pointer then walks both upward paths, so both cover the same total distance and they arrive at the first shared node at the same moment. This is the same trick as finding where two linked lists merge, and it needs no depth counting.
- Set a = p and b = q.
- While a != b: a = (a == null) ? q : a.parent, and b = (b == null) ? p : b.parent.
- Say p is x steps below the answer, q is y steps below it, and the answer is r steps below the root. Pointer a goes up x + r steps to the root, one more to null, jumps to q, and climbs y more: it reaches the answer after x + r + 2 + y steps. Pointer b needs y + r + 2 + x. Equal, so they meet there (or sooner, at the answer itself, when x == y).
- Return a.
class Solution {
public Node lowestCommonAncestor(Node p, Node q) {
Node a = p, b = q;
while (a != b) {
a = (a == null) ? q : a.parent;
b = (b == null) ? p : b.parent;
}
return a;
}
}class Solution:
def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':
a, b = p, q
while a is not b:
a = q if a is None else a.parent
b = p if b is None else b.parent
return aclass Solution {
public:
Node* lowestCommonAncestor(Node* p, Node* q) {
Node* a = p;
Node* b = q;
while (a != b) {
a = (a == nullptr) ? q : a->parent;
b = (b == nullptr) ? p : b->parent;
}
return a;
}
};function lowestCommonAncestor(p, q) {
let a = p, b = q;
while (a !== b) {
a = (a === null) ? q : a.parent;
b = (b === null) ? p : b.parent;
}
return a;
}Edge cases to test
- p is an ancestor of q (or the other way round): the answer is p itself
- One of the two nodes is the root
- p and q are siblings
- p and q are at very different depths
- A tree with only two nodes
- A very deep tree (a long chain), where recursion could overflow but walking up with a loop is fine
Hints
Hint 1
You are not given the root, only the two nodes. What can you reach from a node by following parent links?
Hint 2
Every ancestor of p lies on the path from p up to the root. Write those down, then walk up from q until you meet one of them.
Hint 3
Think of the two upward paths as two linked lists that merge at the answer and share the same tail up to the root. Two pointers that each walk both paths, one after the other, cover the same distance and meet exactly at the merge point.
FAQ
What is the best time complexity for Lowest Common Ancestor of a Binary Tree III?
Optimal (two pointers that switch paths) runs in O(h) time and O(1) extra space. Each pointer walks at most both upward paths, which is at most 2h + 2 steps.
Which pattern does Lowest Common Ancestor of a Binary Tree III use?
It is a trees & bst problem that uses the lca pattern. Other problems with the same pattern: Lowest Common Ancestor of a Binary Tree, Lowest Common Ancestor of a Binary Search Tree, Smallest Common Region.
Is there a brute force solution for Lowest Common Ancestor of a Binary Tree III?
Yes. Ancestor set takes O(h) time and O(h) space. Walk from p up to the root and put every node on the way into a hash set.
Which edge cases should I test for Lowest Common Ancestor of a Binary Tree III?
p is an ancestor of q (or the other way round): the answer is p itself; One of the two nodes is the root; p and q are siblings; p and q are at very different depths; A tree with only two nodes; A very deep tree (a long chain), where recursion could overflow but walking up with a loop is fine.