Navigate Between Nodes in a Recursively Defined Binary Tree
Trees & GraphsModel answerLast updated
Determine the path between two nodes in a Fibonacci-style binary tree using only their preorder indices, without building the tree in memory.
Problem
A binary tree structure is defined recursively by an order parameter n:
- When
n = 0: the tree contains exactly one node - When
n = 1: the tree contains exactly one node - When
n > 1: the tree has a root with left subtree of ordern-1and right subtree of ordern-2
Nodes are numbered sequentially starting from 1 using preorder traversal (visit root, then left subtree, then right subtree).
Write a function that takes three inputs:
n: the tree order (0 ≤ n ≤ 80)u: the starting node indexv: the destination node index
Return a string describing the shortest path from node u to node v using these characters:
'L': move to left child'R': move to right child'P': move to parent
Constraints
- The tree order
ncan be as large as 80 - Node indices are 1-based
- You cannot construct the tree in memory (it may contain over 10^16 nodes)
- All movements must follow valid parent-child edges
Examples
Example 1:
Input: n = 2, u = 2, v = 3
The tree has structure: root (index 1), left child (index 2), right child (index 3)
Path: go up from 2 to root, then right to 3
Output: "PR"
Example 2:
Input: n = 4, u = 2, v = 9
The tree has 9 nodes total. Node 2 is in the left subtree, node 9 is in the right subtree
Output: "PRR"
Example 3:
Input: n = 3, u = 1, v = 1
Same node
Output: ""
Hints
Hint 1
Calculate how many nodes exist in a tree of order k using the recursive definition. This follows a pattern similar to Fibonacci numbers.
Hint 2
Given a node's index and the current subtree order, you can determine whether it lies in the left subtree, right subtree, or is the root itself by comparing index ranges.
Hint 3
The shortest path between two nodes always passes through their lowest common ancestor. Find where the root-to-node paths diverge.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires navigating a massive tree structure using only index arithmetic. The key insight is that preorder numbering assigns contiguous index ranges to subtrees, allowing us to locate any node without materializing the tree.
Computing subtree sizes
Let N(k) represent the number of nodes in a tree of order k. From the recursive definition:
N(0) = 1N(1) = 1N(k) = 1 + N(k-1) + N(k-2)fork > 1
This produces the sequence: 1, 1, 3, 5, 9, 15, 25, 41, 67, ...
The formula is N(k) = 2·F(k+1) - 1 where F denotes the Fibonacci sequence starting F(1) = F(2) = 1. For n = 80, the tree contains roughly 7.6 × 10^16 nodes, which fits in a 64-bit integer.
Precompute this array once in O(n) time.
Locating nodes via index ranges
In preorder traversal, if a subtree of order k starts at root index r:
- The root occupies index
r - The left subtree (order
k-1) occupies indices[r+1, r+N(k-1)] - The right subtree (order
k-2) occupies indices[r+1+N(k-1), r+N(k)]
To find a target node, start at the overall root (index 1, order n) and repeatedly:
- If target equals current root, stop
- Otherwise, calculate where the right subtree begins:
right_start = current_root + 1 + N(current_order - 1) - If
target < right_start, descend left (order decreases by 1) - Otherwise, descend right (order decreases by 2)
- Record the direction taken
This produces a sequence of directions from root to the target node.
Finding the path via LCA
The shortest path between two nodes in a tree must pass through their lowest common ancestor (LCA). Since our direction sequences uniquely identify node positions:
- Generate the root-to-u path:
path_u - Generate the root-to-v path:
path_v - Find the longest common prefix (this represents the path to the LCA)
- The answer is:
'P'repeated for each step ofpath_uafter the common prefix (climbing from u to LCA)- Followed by the directions in
path_vafter the common prefix (descending from LCA to v)
Complexity
Time: O(n)
- Precomputing sizes: O(n)
- Each descent: O(n) worst case (tree height is O(n))
- Total: O(n) per query
Space: O(n)
- Size array: O(n)
- Two path arrays: O(n) combined
- Output string: O(n)
Edge cases
u == v: return empty string- One node is ancestor of the other: result contains only P's or only L/R's
n = 0orn = 1: single-node tree, only valid query is (1,1)- Invalid indices outside
[1, N(n)]: should raise an error
Implementation
def get_fibonacci_path(n, u, v):
# Compute node counts for each order
node_count = [1] * max(2, n + 1)
for i in range(2, n + 1):
node_count[i] = 1 + node_count[i - 1] + node_count[i - 2]
total_nodes = node_count[n]
if not (1 <= u <= total_nodes and 1 <= v <= total_nodes):
raise ValueError(f"Invalid node index: must be in [1, {total_nodes}]")
def find_path_from_root(target):
"""Return direction sequence from root to target node."""
path = []
current_root = 1
current_order = n
while target != current_root:
# Target is inside this subtree, so order >= 2
left_size = node_count[current_order - 1]
right_start = current_root + 1 + left_size
if target < right_start:
# Target is in left subtree
path.append('L')
current_root = current_root + 1
current_order = current_order - 1
else:
# Target is in right subtree
path.append('R')
current_root = right_start
current_order = current_order - 2
return path
# Generate paths from root to each target
path_to_u = find_path_from_root(u)
path_to_v = find_path_from_root(v)
# Find common prefix (path to LCA)
common_len = 0
while (common_len < len(path_to_u) and
common_len < len(path_to_v) and
path_to_u[common_len] == path_to_v[common_len]):
common_len += 1
# Build result: climb from u to LCA, then descend to v
climb_steps = 'P' * (len(path_to_u) - common_len)
descend_steps = ''.join(path_to_v[common_len:])
return climb_steps + descend_steps
Example trace
For n = 4, u = 2, v = 9:
node_count = [1, 1, 3, 5, 9]- Finding path to node 2:
- Start at (root=1, order=4)
- Right subtree starts at 1 + 1 + 5 = 7
- 2 < 7, so go left → path_to_u =
['L']
- Finding path to node 9:
- Start at (root=1, order=4), right starts at 7
- 9 ≥ 7, so go right to (root=7, order=2)
- Right subtree starts at 7 + 1 + 1 = 9
- 9 ≥ 9, so go right → path_to_v =
['R', 'R']
- Common prefix length = 0
- Result:
'P' * 1 + 'RR' = "PRR"
What makes this hard
- Recognizing that tree construction is infeasible and index arithmetic is necessary
- Correctly deriving the node count recurrence
- Understanding how preorder numbering partitions index ranges
- Identifying the LCA pattern in the solution
- Handling all edge cases cleanly (same node, ancestor relationships, boundary indices)