Shared Ancestors: Binary Tree to Multi-Parent Graph
Trees & GraphsModel answerLast updated
Find the lowest common ancestor of two nodes in a binary tree, then generalize to a directed acyclic graph where several incomparable lowest common ancestors can exist.
Part 1: Binary tree
You are given the root of a binary tree and two nodes p and q that belong to it. Return the deepest node that has both p and q in its subtree. A node counts as part of its own subtree, so if p is an ancestor of q, the answer is p.
Write findTreeLCA(root, p, q).
Example
root = [3, 5, 1, 6, 2, 0, 8], p = 5, q = 1
Output: 3
Node 3 is the deepest node whose subtree contains both 5 and 1.
Part 2: Directed acyclic graph
Now the structure is a DAG in which a node may have several parents. A node A is a lowest common ancestor of p and q if:
Ais an ancestor of bothpandq(a node is an ancestor of itself), and- no descendant of
Ais also a common ancestor ofpandq.
Because ancestors no longer lie on a single chain, there may be more than one such node. Design an algorithm that returns all of them.
Small illustration: if C is a parent of D and E, and both D and E are parents of F, then C is an ancestor of F. When two nodes share several ancestors, you want only the deepest, mutually incomparable ones.
What to deliver
- A working
findTreeLCA(root, p, q)withO(N)time. - An algorithm for the DAG case, with a justification that it returns exactly the right set, and its complexity.
- Discussion of edge cases (
p == q, one node an ancestor of the other, no common ancestor, a node missing from the structure).
Constraints
N(number of nodes) is up to10^5.- Tree solution:
O(N)time. - DAG solution: state your own time and space complexity.
Hints
Hint 1
For the tree, think about what each recursive call can report to its parent: whether it found `p`, `q`, both, or neither. Where do the two reports first meet?
Hint 2
With N up to 10^5 a skewed tree is very deep. Consider an iterative version that records a parent for each node and then walks upward from `p` and `q`.
Hint 3
For the DAG, compute the full ancestor set of `p` and of `q` (walking parent edges), intersect them, then discard any common ancestor that still has a child inside the intersection.
Hint 4
Why is checking only direct children enough? If a common ancestor has a deeper common-ancestor descendant, the first step on the path toward it is a child that is also a common ancestor.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Tree
Recursive approach
Do a post-order traversal where each call answers: "which target, or which LCA, lives in this subtree?"
- If the node is
None,p, orq, return it. - Recurse into the left and right children.
- If both recursive results are non-null,
pandqsit in different subtrees, so the current node is the LCA. - Otherwise return whichever result is non-null.
def lca_recursive(node, p, q):
if node is None or node is p or node is q:
return node
left = lca_recursive(node.left, p, q)
right = lca_recursive(node.right, p, q)
if left and right:
return node
return left or right
When one target is an ancestor of the other, that target returns itself immediately and the other is never needed, which matches the "a node is its own descendant" rule.
Iterative approach (safe at N = 10^5)
A chain-shaped tree has depth 10^5, which breaks default recursion limits in many languages. Use parent pointers instead:
- Traverse with an explicit stack, recording
parent[child] = node, until bothpandqhave been seen. - Walk from
pto the root, storing every node in a set. - Walk from
qupward; the first node found in the set is the LCA.
In a tree, ancestors of a node form one path to the root, and the two paths merge and then stay merged. The first shared node met from q is therefore the deepest one.
Complexity: O(N) time, O(N) extra space (the recursive version uses O(H)).
Part 2: DAG
Algorithm
- Build
parentsandchildrenadjacency lists from the edge list. - BFS from
palong parent edges to getanc(p)(includingp). Do the same forq. - Let
C = anc(p) ∩ anc(q). - Return every
ainCthat has no child inC.
Why checking only children is enough
Suppose a in C has a proper descendant d that is also in C. Take a path from a to d and let c be the first node after a. Then c is an ancestor of d, and d is an ancestor of both targets, so c is an ancestor of both targets too. Hence c is in C and a is correctly removed. The converse is immediate: if a has no child in C, no descendant of it can be in C, because any such descendant would force a child into C by the same argument.
If C is non-empty the result is non-empty: follow child edges inside C; since the graph is acyclic this must stop at a node with no child in C.
Examples
- Edges
C→D, C→E, D→F, E→F, withp = F,q = D:anc(F) = {F, D, E, C},anc(D) = {D, C}, soC = {D, C}.Chas childDin the set and is dropped. Answer:{D}. - Edges
A→X, B→X, A→Y, B→Y, withp = X,q = Y: bothAandBsurvive. Answer:{A, B}. This is why the function returns a set.
Complexity
- Per query:
O(V + E)time andO(V)space (two BFS runs plus one filter pass over child edges ofC). - Many queries: precompute ancestor sets in topological order,
anc(v) = {v} ∪ ⋃ anc(parent). Worst case this isO(V²)memory; with bitsets aboutV²/8bytes, roughly 1.25 GB atV = 10^5. This is only worthwhile with many queries on a modest graph.
Code
from collections import defaultdict, deque
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def findTreeLCA(root, p, q):
if root is None:
return None
parent = {root: None}
stack = [root]
while stack and (p not in parent or q not in parent):
node = stack.pop()
for child in (node.left, node.right):
if child is not None:
parent[child] = node
stack.append(child)
if p not in parent or q not in parent:
return None
seen = set()
node = p
while node is not None:
seen.add(node)
node = parent[node]
node = q
while node not in seen:
node = parent[node]
return node
def findDagLCAs(edges, p, q):
children, parents = defaultdict(list), defaultdict(list)
for u, v in edges:
children[u].append(v)
parents[v].append(u)
def ancestors(start):
seen = {start}
dq = deque([start])
while dq:
x = dq.popleft()
for par in parents[x]:
if par not in seen:
seen.add(par)
dq.append(par)
return seen
common = ancestors(p) & ancestors(q)
return {a for a in common if not any(c in common for c in children[a])}
Edge cases
p == q: both versions returnp(tree) or{p}(DAG).pis an ancestor ofq: the answer isp/{p}.- No common ancestor (disconnected components in the DAG): return an empty set.
- Target missing from the tree: the recursive version would wrongly return the one target it finds, so state your assumption or validate membership first. The iterative version returns
None. - Compare nodes by identity, not value, in case values repeat.
Common mistakes
- Using unbounded recursion on a deep tree.
- Returning a single node for the DAG case and missing incomparable answers.
- Filtering by "has the fewest ancestors" or "deepest by depth", which is wrong because depth is not well defined with multiple parents and incomparable nodes may have different depths.
- Forgetting that a node is its own ancestor.
Follow-ups
- Many tree queries: binary lifting (
O(N log N)build,O(log N)query) or Euler tour plus sparse table (O(1)query), or offline Tarjan with union-find. - BST variant: compare values and descend in
O(H). - Parent pointers given: treat it as intersecting two linked lists.