Music streaming app~20 min2s · 256 MBtarget O(n) time, O(h) spaceclassic twin: lc-173tree-recursion
A music streaming app keeps its track ids in a search tree. The player steps through the tracks from the smallest id to the largest, one at a time, and sometimes asks whether any track is left.
The tree can hold 100,000 tracks, and the player may read only a few of them. Your team lead does not want the whole tree copied into a list first.
Write step_through(values, left, right, commands).
0 to n - 1, and track 0 is the top of the tree. An empty tree has three empty lists.values[i] is the id of track i. left[i] and right[i] are the tracks on its left and right, or -1 where there is none. The tree is a search tree with distinct ids.commands is a list of steps for one player. A 0 asks whether an id is left, and a 1 takes the next id. The player starts before the smallest id.0, answer 1 when an id is left and 0 when not. For a 1, answer the next id in increasing order, or -1 when none is left. A take with nothing left changes nothing.Input: values = [8, 3, 10, 1, 6, 14, 4, 7, 13], left = [1, 3, -1, -1, 6, 8, -1, -1, -1], right = [2, 4, 5, -1, 7, -1, -1, -1, -1], commands = [1, 1, 0, 1, 1, 1]
Output: [1, 3, 1, 4, 6, 7]The takes give 1, 3, 4, 6 and 7, and the question after the second take is answered with 1. The stack always holds the path down to the next id, so the top is the next answer.
| Command | Answer | Stack after (ids, top last) |
|---|---|---|
| take next | 1 | [8, 3] |
| take next | 3 | [8, 6, 4] |
| has next | 1 | [8, 6, 4] |
| take next | 4 | [8, 6] |
| take next | 6 | [8, 7] |
| take next | 7 | [8] |
Input: values = [5], left = [-1], right = [-1], commands = [1, 0, 1]
Output: [5, 0, -1]Input: values = [], left = [], right = [], commands = [0, 1]
Output: [0, -1]0 ≤ length of values = length of left = length of right ≤ 10^51 ≤ values[i] ≤ 10^6, and the ids are distinctleft and right is -1 or a track number from 1 to n - 100 ≤ length of commands ≤ 10^5, and every command is 0 or 1A player can take all 100,000 tracks of a chain-shaped tree. Searching from the top for the next larger id on each take costs about n steps each time, and n^2 / 2 steps in total.
A stack that remembers the place of the walk makes every take cost one step on average: each track is pushed once and taken once.