Music streaming app~15 min2s · 256 MBtarget O(h) time, O(h) spaceclassic twin: lc-700tree-recursion
A video app keeps its video ids in a search tree. A search for an id starts at the top and compares the id with the video it meets. A smaller id continues on the left, and a larger id on the right.
For capacity planning, the team wants the trail of each lookup: the ids it compared, in order. The tree can hold 100,000 videos, and some trees are very deep.
Write lookup_path(values, left, right, key).
0 to n - 1, and video 0 is the top of the tree. An empty tree has three empty lists.values[i] is the id of video i. left[i] and right[i] are the videos on its left and right, or -1 where there is none.key from the top. Return the ids it was compared with, in order. If the key is in the tree, it is the last id. If not, the trail ends at the last video before a missing child.Input: values = [50, 30, 70, 20, 40, 60, 80, 35], left = [1, 3, 5, -1, 7, -1, -1, -1], right = [2, 4, 6, -1, -1, -1, -1, -1], key = 35
Output: [50, 30, 40, 35]| Step | What happens | Trail |
|---|---|---|
| [1] | Start at the top, the id 50 | |
| [2], [4] | 50 is not 35, and 35 is smaller, so go left | [50] |
| [2], [4] | 30 is not 35, and 35 is larger, so go right | [50, 30] |
| [2], [4] | 40 is not 35, and 35 is smaller, so go left | [50, 30, 40] |
| [2], [3] | 35 is the key, so stop | [50, 30, 40, 35] |
Input: values = [50, 30, 70, 20, 40, 60, 80, 35], left = [1, 3, 5, -1, 7, -1, -1, -1], right = [2, 4, 6, -1, -1, -1, -1, -1], key = 65
Output: [50, 70, 60]65 is larger than 50, smaller than 70, and larger than 60. The video 60 has no right child, so the walk ends there.
Input: values = [], left = [], right = [], key = 5
Output: []An empty tree compares nothing.
0 ≤ n ≤ 100,000 and 1 ≤ values[i] ≤ 10^9, and the ids are distinctleft and right is -1 or a video number from 1 to n - 101 ≤ key ≤ 10^9Videos can arrive in sorted order, so the tree can be a chain of 100,000. A lookup then walks up to 100,000 steps.
A lookup never visits more than one video on each level, so its cost is the height of the tree. Copying the trail at every step would cost the height squared, which is about 5 billion steps for a chain.