Route Between Two Nodes of an Implicit Recursive Tree
Trees & GraphsAuto-graded · 21 test casesLast 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 ofG(k-1)and whose right subtree is a copy ofG(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 <= 80aandbare 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Never build the tree. With pre-order numbering, the sizes of the subtrees are enough to navigate.
- Compute
size(0..order)usingsize(0) = size(1) = 1andsize(k) = 1 + size(k-1) + size(k-2). - For a target node
t, find its root-to-node path. Start withroot = 1andk = order. Then repeat:- Record
root. Ift == root, stop. - The left subtree covers numbers
root+1 .. root+size(k-1). Iftis in that range, move to the left child:root += 1,k -= 1. - Otherwise
tis in the right subtree, which starts atroot + 1 + size(k-1):root += 1 + size(k-1),k -= 2.
- Record
- Compute the root paths for
aandb. They agree on a common prefix whose last entry is the lowest common ancestor (LCA), then diverge. - The answer is the part of
a's path below the LCA, reversed (going up), then the LCA, then the part ofb's path below the LCA (going down).
Why it is correct
In pre-order, a subtree's numbers are: its root, then the whole left subtree as a contiguous block, then the whole right subtree as a contiguous block. These three parts partition the subtree's numbers, so exactly one of them contains the target and the descent is forced.
In a tree, root-to-node paths are unique. Two of them share exactly the prefix up to the LCA, and the unique simple path between two nodes passes through their LCA, so it is also the shortest.
Edge cases fall out naturally. If a == b, both paths are equal, so the result is [a]. If one node is an ancestor of the other, one path is a prefix of the other and the LCA is the shallower node. For order 0 or 1, the tree is a single node.
Complexity
- Time:
O(order). Each descent step reduceskby at least 1, so each root path has at mostorder + 1entries. Computing the sizes, comparing prefixes and joining the paths are all linear in that. - Space:
O(order)for the size table and the two root paths.
Reference solution
from typing import List
def tree_route_between(order: int, a: int, b: int) -> List[int]:
# sizes[k] = number of nodes in G(k)
sizes = [1] * (max(order, 1) + 1)
for k in range(2, order + 1):
sizes[k] = 1 + sizes[k - 1] + sizes[k - 2]
def root_to_node(target: int) -> List[int]:
path = []
root = 1
k = order
while True:
path.append(root)
if target == root:
return path
left_size = sizes[k - 1]
if target <= root + left_size:
root += 1
k -= 1
else:
root += 1 + left_size
k -= 2
path_a = root_to_node(a)
path_b = root_to_node(b)
# number of shared leading entries; the last shared one is the LCA
common = 0
while (common < len(path_a) and common < len(path_b)
and path_a[common] == path_b[common]):
common += 1
lca = path_a[common - 1]
return path_a[common:][::-1] + [lca] + path_b[common:]