KatInterview

Identify the Nearest Shared Ancestor of Two Tree Nodes

Trees & GraphsAuto-graded · 18 test cases
MediumAuto-gradedTrees & Graphsbinary-treetree-traversalancestor-search

Last updated

Tests tree reconstruction and ancestor tracking to locate the closest common parent of two given values in a binary tree.

You are given a binary tree represented as a level-order array where null indicates a missing child node. You are also given two distinct integer values p and q that are guaranteed to appear in the tree.

Your task is to return the value of the nearest shared ancestor of nodes p and q. The nearest shared ancestor is the deepest node in the tree that has both p and q as descendants. Note that a node is considered a descendant of itself.

Input Format

  • tree: A list representing the binary tree in level-order (breadth-first) traversal. None values represent absent nodes.
  • p: An integer value present in the tree.
  • q: An integer value present in the tree.

Output Format

Return the integer value of the nearest shared ancestor node.

Constraints

  • All non-null values in the tree are unique.
  • The tree contains between 2 and 100,000 nodes.
  • Both p and q are guaranteed to exist in the tree.
  • p ≠ q

Examples

Example 1

Input: find_nearest_ancestor([3, 5, 1, 6, 2, 0, 8], 5, 1)

Output: 3

Example 2

Input: find_nearest_ancestor([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 5, 4)

Output: 5

Hints

Hint 1

Build a parent mapping by reconstructing the tree from its level-order representation.

Hint 2

Walk upward from one target node and record all ancestors you visit.

Hint 3

Starting from the other target node, walk upward until you encounter a previously recorded ancestor.