Deepest Shared Ancestor of Two Nodes in a Rooted Tree
Trees & GraphsAuto-graded · 19 test casesLast updated
Find the deepest node whose subtree contains two given nodes in a tree stored as child lists, using a single depth-first pass that stays safe on very deep trees.
Deepest Shared Ancestor of Two Nodes in a Rooted Tree
A rooted tree has nodes labeled 0 to n - 1. The tree is given as a list of child lists: children[v] holds the labels of the direct children of node v. A node with no children has an empty list.
You are given the label of the root, root, and two node labels p and q.
Return the label of the lowest common ancestor of p and q: the deepest node whose subtree contains both p and q.
Precise rules
- The tree consists only of the nodes reachable from
rootby following child lists. Nodes that cannot be reached fromrootare not part of the tree. - A node belongs to its own subtree. So if one of the two nodes is an ancestor of the other, that node itself is the answer.
- If
pandqare the same label, the answer is that label. - If
porqis not reachable fromroot, returnNone. - The answer is uniquely defined by the tree structure. The order of the children inside a list does not change the result.
- The result is a node label (an integer), not a position or a depth.
Function
Implement shared_ancestor(children, root, p, q).
children:List[List[int]], wherechildren[v]lists the children ofv.root:int, the label of the root.p,q:int, node labels.
Constraints
1 <= n <= 10^5, wheren = len(children).- Every label appearing in
root,p,qor in any child list is in the range0ton - 1. - Starting from
root, the child lists form a valid tree: no node is reached twice and there are no cycles. - The tree may be very unbalanced, up to a single chain of 10^5 nodes, so avoid relying on deep recursion.
Examples
Example 1
Input: shared_ancestor([[1, 2, 3], [4, 5], [6], [], [], [], []], 0, 4, 5)
Output: 1
Example 2
Input: shared_ancestor([[1, 2, 3], [4, 5], [6], [], [], [], []], 0, 4, 6)
Output: 0
Example 3
Input: shared_ancestor([[1], [2, 3], [], []], 0, 1, 2)
Output: 1
Hints
Hint 1
For each node, ask two questions about its subtree: does it contain p, and does it contain q? Combine the answers from the children with the check on the node itself.
Hint 2
If you finish nodes in post-order (children before parent), the first node to report that its subtree contains both p and q must be the deepest such node. This also covers the case where one target is an ancestor of the other, or p equals q.
Hint 3
Deep chains can exceed Python's recursion limit. Simulate the DFS with an explicit stack, pushing each node once on entry and once more to mark that its children are done.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Run a depth-first traversal in post-order from root, so every node is processed only after all of its children. For each node compute two flags:
- whether
pis in its subtree (the node itself counts), - whether
qis in its subtree.
A node sets a flag if it equals the target, or if any child reported that flag. The first node, in the order nodes finish, that has both flags set is the answer. Record it once and never overwrite it.
Because a tree with 10^5 nodes can be a long chain, the DFS uses an explicit stack instead of recursion. Each node is pushed twice: once to expand its children, and once (marked as "exiting") to compute its flags after its children have finished.
Only nodes reachable from root are ever visited. If p or q is not among them, no node ever gets both flags, so the answer stays None.
Why it is correct
Let L be the first node to finish with both flags set.
Lis a common ancestor, since bothpandqlie in its subtree.- No child of
Lhas both flags. If one did, it would have finished beforeL(post-order) with both flags set, contradicting thatLis first. So eitherpandqare in different child subtrees ofL, or one of them isLitself. In both cases no deeper node contains both. - Ancestors of
Lalso end up with both flags, but they finish later, and the answer is not overwritten.
If one target is an ancestor of the other, that ancestor matches its own label and inherits the other flag from below, so it is returned without special-casing. If p == q, the node with that label sets both flags on itself, and since all its descendants cannot have both flags, it is the first to finish with both set.
Complexity
- Time: O(n), each node and edge is handled a constant number of times.
- Space: O(n) for the flag dictionary and the stack (the stack alone is O(height)).
Reference solution
from typing import List
def shared_ancestor(children: List[List[int]], root: int, p: int, q: int) -> int:
# Iterative post-order DFS; each finished node stores flags telling
# whether p and q occur in its subtree.
found = {}
answer = None
stack = [(root, False)]
while stack:
node, exiting = stack.pop()
if not exiting:
stack.append((node, True))
for child in reversed(children[node]):
stack.append((child, False))
else:
has_p = node == p
has_q = node == q
for child in children[node]:
child_has_p, child_has_q = found[child]
has_p = has_p or child_has_p
has_q = has_q or child_has_q
found[node] = (has_p, has_q)
# Descendants finish before ancestors, so the first node with
# both flags set is the lowest common ancestor.
if has_p and has_q and answer is None:
answer = node
return answer