Fibonacci Tree Path
MediumTrees · Databricks
A Fibonacci tree of order n is defined recursively:
- Orders
0and1are a single node. - For
n >= 2, the tree is a root whose left subtree is a Fibonacci tree of ordern - 2and whose right subtree is a Fibonacci tree of ordern - 1.
Nodes are numbered 0, 1, 2, ... in preorder (a node, then its whole left subtree, then its whole right subtree). For example, the order-4 tree is numbered like this:
text
0
/ \
1 4
/ \ / \
2 3 5 6
/ \
7 8Given n and two node numbers start and dest, return the shortest path from start to dest as a string: first one "U" for each step up to a parent, then "L"/"R" for each step down to a left/right child. Return "" if start == dest.
The tree can have trillions of nodes, so it cannot be built explicitly.
Example 1
- Input:
- n = 4, start = 3, dest = 7
- Output:
- "UURRL"
- Explanation
- Node 3 is reached from the root by L, R and node 7 by R, R, L. Their lowest common ancestor is the root, so go up twice and then down R, R, L.
Example 2
- Input:
- n = 4, start = 0, dest = 8
- Output:
- "RRR"
- Explanation
- From the root, node 8 is the right child of the right child of the right child.
Example 3
- Input:
- n = 4, start = 6, dest = 4
- Output:
- "U"
- Explanation
- Node 6 is the right child of node 4, so a single step up reaches it.
Constraints
0 <= n <= 700 <= start, dest < size(n), wheresize(0) = size(1) = 1andsize(n) = 1 + size(n - 2) + size(n - 1)