Fibonacci Tree Path
DatabricksOnsiteMedium
A Fibonacci tree of order k, written T(k), is a binary tree defined recursively: T(1) and T(2) are each a single node, and for k >= 3, T(k) has a root whose left subtree is T(k-1) and whose right subtree is T(k-2). The nodes are numbered 1, 2, 3, ... in preorder: the root first, then the whole left subtree, then the whole right subtree, so the root is node 1. Let size(k) be the number of nodes in T(k): size(1) = size(2) = 1 and size(k) = 1 + size(k-1) + size(k-2).
Part 1: Path between two nodes
Given the order k of a Fibonacci tree and two node numbers a and b, return the node numbers on the path from a to b in T(k): the list starts with a, ends with b, and lists each node on the path exactly once. If a == b, return [a].
T(k) can have trillions of nodes, so you cannot build the tree.
- Example 1
- a
4- b
9- k
5- Output
[4,3,2,1,7,9]
Why: In
T(5)the root is 1, its left subtreeT(4)holds nodes 2 through 6, and its right subtreeT(3)holds nodes 7 through 9. Node 4 is the left child of 3, which climbs to 2 and then the root 1. Node 9 is the right child of 7, and 7 is the right child of 1. The path rises from 4 to the common ancestor 1 and descends through 7 to 9.
Constraints
1 <= k <= 601 <= a, b <= 3096017511839aandbare node numbers ofT(k)