Bank app~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-449tree-recursion
A bank app keeps the ids of the accounts under review in a binary search tree. Before a nightly shutdown, a job saves the tree as one line of text. After the restart, another job loads the tree back from that text alone.
You write both jobs. The tree can hold up to 200,000 account ids, and every id is different.
Write save_and_load_index(values, left, right).
0 to n - 1, and node 0 is the root. values[i] is the account id of node i.left[i] and right[i] are the numbers of the children of node i, or -1 where there is none. The tree is a binary search tree.# for a missing child of a node that is in the tree. Drop every # at the end. An empty tree is the empty text.Input: values = [30, 20, 40, 10, 25, 35], left = [1, 3, 5, -1, -1, -1], right = [2, 4, -1, -1, -1, -1]
Output: ["30,20,10,25,40,35", "30,20,40,10,25,35"]The preorder walk visits 30, then the left subtree 20, 10, 25, then the right subtree 40, 35. Loading reads the ids back with the open-path stack, as the table shows. The loaded tree is the same tree, written level by level.
| Id read | Open path before (ids) | Removed, in order | Attached as |
|---|---|---|---|
| 30 | none | none | the root |
| 20 | 30 | none | left child of 30 |
| 10 | 30, 20 | none | left child of 20 |
| 25 | 30, 20, 10 | 10, 20 | right child of 20 |
| 40 | 30, 25 | 25, 30 | right child of 30 |
| 35 | 40 | none | left child of 40 |
Input: values = [4, 9], left = [-1, -1], right = [1, -1]
Output: ["4,9", "4,#,9"]The saved text has two ids. The loaded tree has an empty left side for 4, so a # stands for it.
Input: values = [], left = [], right = []
Output: ["", ""]Both texts are empty.
0 ≤ length of values ≤ 2 × 10^5values, left and right have the same length.1 ≤ values[i] ≤ 10^9, and all the ids are different.left and right form a binary search tree rooted at node 0.The saved text of 200,000 ids has about 2.2 million characters, so it must be built once, with a list of pieces or a string builder. A load that inserts the ids from the root costs the depth of the tree for each id, which is 19,999,900,000 steps on a chain.
The tree can be 200,000 levels deep. A function that calls itself for each subtree raises a RecursionError in Python, and risks a stack overflow in Java and C++.