Nearest Shared Ancestor in an Array-Encoded Binary Tree
Trees & GraphsAuto-graded · 20 test casesLast updated
Find the deepest node that is an ancestor of two given values in a binary tree stored as a heap-indexed array, using a parent map and ancestor walk.
Nearest Shared Ancestor
A binary tree is stored in a list tree using heap-style indexing:
- The root is at index
0. - The node at index
ihas its left child at index2*i + 1and its right child at index2*i + 2. - A
Noneentry means there is no node at that position. A position past the end of the list also means there is no node. - Entries below a
Noneposition are never part of the tree. Ignore them.
Every node holds an integer value, and all values in the tree are distinct, so a node can be identified by its value.
You are given the list tree and two values p and q, each of which appears in the tree. Return the value of the lowest common ancestor of the nodes holding p and q. This is the deepest node that has both of them in its subtree. A node counts as being in its own subtree, so if one of the two nodes is an ancestor of the other, that node is the answer. If p == q, the answer is that node itself.
Input
tree:List[Optional[int]], the heap-indexed tree described above.tree[0]is notNone.p:int, the value of the first node.q:int, the value of the second node.
Output
An int, the value of the lowest common ancestor of p and q.
Constraints
2 <= number of nodes in the tree <= 10^5len(tree) <= 10^5-10^9 <= value <= 10^9- All node values are unique.
tree[0]is notNone.pandqare both guaranteed to be values of nodes that are part of the tree.
Examples
Example 1
Input: nearest_shared_ancestor([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 5, 1)
Output: 3
Example 2
Input: nearest_shared_ancestor([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4], 5, 4)
Output: 5
Hints
Hint 1
Each node has exactly one parent, so if you know every node's parent you can walk upward from any node to the root.
Hint 2
Traverse the array from the root, visiting a child only if its slot exists and is not None. Record parent[child_value] = parent_value as you go.
Hint 3
Collect all ancestors of p (including p itself) in a set, then climb from q until you reach a value in that set. That first hit is the answer.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every node except the root has exactly one parent. If we know each node's parent, the path from any node up to the root is determined, and the lowest common ancestor is the first node where the upward path from q meets the upward path from p.
- Build a parent map. Start at index
0and do a breadth-first traversal over array indices. For the node at indexi, look at the slots2*i + 1and2*i + 2. If a slot is inside the list and notNone, that child exists. Recordparent[child_value] = valueand enqueue the child's index. Because we only expand nodes we actually reached, entries hanging below aNoneslot are never visited, which matches the rule that they are not part of the tree. - Collect the ancestors of
p. Starting atp, follow parents up to the root, adding every value (includingp) to a set. - Climb from
q. Starting atq, move up through parents until the current value is in the set. That value is the answer.
Why it is correct
The set holds exactly the nodes on the path from p to the root. Those are all the nodes that have p in their subtree. Climbing from q visits, in order of increasing height, exactly the nodes that have q in their subtree. The first one that is also in the set is therefore a common ancestor, and since we go from the bottom up, it is the lowest one. Because nodes count as their own ancestors, the cases where p is an ancestor of q (or the reverse, or they are equal) are handled automatically: the climb from q stops immediately at p, or at q itself.
The traversal uses a queue and loops instead of recursion, so a very deep, chain-like tree cannot cause a recursion error.
Complexity
- Time: O(n), where n is the length of the list. Each slot is examined at most once, and each upward walk is at most the tree height.
- Space: O(n) for the parent map, the queue, and the ancestor set.
Reference solution
from typing import List, Optional
def nearest_shared_ancestor(tree: List[Optional[int]], p: int, q: int) -> int:
if not tree or tree[0] is None:
raise ValueError("tree must have a root")
# Breadth-first walk from the root, recording each value's parent.
parent = {tree[0]: None}
queue = [0]
head = 0
n = len(tree)
while head < len(queue):
i = queue[head]
head += 1
value = tree[i]
for child_index in (2 * i + 1, 2 * i + 2):
if child_index < n and tree[child_index] is not None:
child = tree[child_index]
parent[child] = value
queue.append(child_index)
# All ancestors of p, including p itself.
ancestors = set()
current = p
while current is not None:
ancestors.add(current)
current = parent[current]
# First ancestor of q (including q) that is also an ancestor of p.
current = q
while current not in ancestors:
current = parent[current]
return current