Identify the Nearest Shared Ancestor of Two Tree Nodes
Trees & GraphsAuto-graded · 18 test casesLast 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.Nonevalues 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
pandqare 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem provides a binary tree in level-order array format. Since we need to find a shared ancestor, we must understand the parent-child relationships. The solution works in three phases:
-
Reconstruct parent relationships: Process the level-order array to build a dictionary mapping each node value to its parent. Use a queue to simulate breadth-first traversal, tracking which index in the input array corresponds to each node's children.
-
Trace one path to root: Starting from node
p, walk upward following parent pointers until reaching the root (where parent isNone). Store every visited node in a set. -
Find intersection: Starting from node
q, walk upward until encountering a node that exists in the ancestor set from step 2. This intersection point is the nearest shared ancestor.
Correctness
Since every node has exactly one path to the root, and we collect all ancestors of p, the first ancestor of q that appears in that set must be the deepest node on both paths. By walking upward from q, we encounter ancestors in order from closest to farthest, guaranteeing we find the nearest one first.
The algorithm correctly handles cases where one node is an ancestor of the other: when p is an ancestor of q (or vice versa), the ancestor set will contain p, and walking from q will eventually reach p itself.
Complexity
-
Time: O(n) where n is the number of nodes. Building the parent mapping requires processing each node once during reconstruction. Walking to the root from both
pandqis bounded by tree height h, which is at most n. -
Space: O(n) for the parent dictionary and ancestor set. In the worst case (a completely unbalanced tree), the ancestor set could contain n nodes.
Implementation
from typing import List, Optional
def find_nearest_ancestor(tree: List[Optional[int]], p: int, q: int) -> int:
# Build parent mapping from level-order array representation
parent = {tree[0]: None}
queue = [tree[0]]
index = 1
head = 0
while head < len(queue) and index < len(tree):
node = queue[head]
head += 1
for _ in range(2):
if index >= len(tree):
break
child = tree[index]
index += 1
if child is not None:
parent[child] = node
queue.append(child)
# Collect all ancestors of p
ancestors = set()
node = p
while node is not None:
ancestors.add(node)
node = parent[node]
# Walk upward from q until we hit an ancestor of p
node = q
while node not in ancestors:
node = parent[node]
return node