KatInterview

Nearest Shared Ancestor in an Array-Encoded Binary Tree

Trees & GraphsAuto-graded · 20 test cases
EasyAuto-gradedTrees & Graphsbinary-treelowest-common-ancestorbfs

Last 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 i has its left child at index 2*i + 1 and its right child at index 2*i + 2.
  • A None entry 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 None position 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 not None.
  • 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^5
  • len(tree) <= 10^5
  • -10^9 <= value <= 10^9
  • All node values are unique.
  • tree[0] is not None.
  • p and q are 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.