KatInterview

Route Between Two Nodes of an Implicit Recursive Tree

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphstreelcarecursion

Last updated

Find the unique path between two pre-order-indexed nodes in a huge recursively defined tree, using subtree sizes to navigate without building it.

Route Between Two Nodes of an Implicit Recursive Tree

A family of binary trees G(k) is built recursively:

  • G(0) is a single node.
  • G(1) is a single node.
  • For k >= 2, G(k) has a root whose left subtree is a copy of G(k-1) and whose right subtree is a copy of G(k-2).

Let size(k) be the number of nodes in G(k). By the definition above, size(0) = size(1) = 1 and size(k) = 1 + size(k-1) + size(k-2) for k >= 2. This gives 1, 1, 3, 5, 9, 15, ....

Nodes of G(order) are numbered 1, 2, 3, ... in pre-order: the root gets the number 1, then the whole left subtree is numbered, then the whole right subtree. So if a subtree's root has number r and the subtree has a left child, the left subtree occupies the next size(k-1) numbers after r, and the right subtree occupies the numbers after that.

For example, in G(3) the root is 1, its left child (the root of G(2)) is 2, that node's children are 3 (left, a G(1)) and 4 (right, a G(0)), and the root's right child (a G(1)) is 5.

Given the integer order and two node numbers a and b, return the shortest path from a to b as a list of node numbers, starting with a and ending with b. Consecutive entries must be parent and child in the tree, in either direction. In a tree this path is unique.

The tree can contain tens of quadrillions of nodes, so it must not be built explicitly. Your running time should be proportional to order.

Details

  • If a == b, return [a].
  • If one node is an ancestor of the other, the path is just the straight line between them.

Constraints

  • 0 <= order <= 80
  • a and b are valid node numbers: 1 <= a, b <= size(order).
  • size(80) is about 4.7 * 10^16, which fits in a signed 64-bit integer.
  • Target time complexity: O(order).

Examples

Example 1

Input: tree_route_between(3, 1, 3)

Output: [1, 2, 3]

Hints

Hint 1

You never need the tree itself: with pre-order numbering, the sizes of G(0)..G(order) tell you which subtree any node number falls into.

Hint 2

To find the root-to-node path for a target t, keep the current subtree's root number r and order k. If t == r you are done. If t <= r + size(k-1) go left (r+1, k-1). Otherwise go right (r + 1 + size(k-1), k-2).

Hint 3

Compute the root-to-node path for both a and b. They share a common prefix that ends at the lowest common ancestor. The answer is a's path reversed back up to that ancestor, followed by b's path below it.