KatInterview

Shared Ancestors: Binary Tree to Multi-Parent Graph

Trees & GraphsModel answer
MediumModel answerTrees & Graphslowest-common-ancestorbinary-treedag

Last 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:

  • A is an ancestor of both p and q (a node is an ancestor of itself), and
  • no descendant of A is also a common ancestor of p and q.

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

  1. A working findTreeLCA(root, p, q) with O(N) time.
  2. An algorithm for the DAG case, with a justification that it returns exactly the right set, and its complexity.
  3. 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 to 10^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.