KatInterview

Deepest Shared Ancestor of Two Nodes in a Rooted Tree

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphstreedfslowest-common-ancestor

Last 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 root by following child lists. Nodes that cannot be reached from root are 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 p and q are the same label, the answer is that label.
  • If p or q is not reachable from root, return None.
  • 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]], where children[v] lists the children of v.
  • root: int, the label of the root.
  • p, q: int, node labels.

Constraints

  • 1 <= n <= 10^5, where n = len(children).
  • Every label appearing in root, p, q or in any child list is in the range 0 to n - 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.