Search~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-606tree-recursion
A search service plans every query as a tree of steps. Each step has a number, and the two inputs of a step are its left and right children. A plan can have up to 200,000 steps.
For the logs, the team writes each plan as one line of text, so that two plans can be compared with an ordinary text diff. Your team lead asks: "Write the plan as nested brackets, and make sure two different plans never give the same line."
Write plan_to_text(values, left, right).
0 to n - 1, and node 0 is the root.values[i] is the number of step i. left[i] and right[i] are the numbers of its left and right children, or -1 where there is none.() for the left side. A node with a left child and no right child writes nothing for the right side."" when values is empty.Input: values = [4, 2, 6, 3, 1, 5], left = [1, 3, 5, -1, -1, -1], right = [2, 4, -1, -1, -1, -1]
Output: "4(2(3)(1))(6(5))"The root 4 has children 2 and 6. Node 2 has the leaves 3 and 1. Node 6 has only a left child, 5, so it writes one bracket pair and nothing for the right side.
| Node | Value | Text written so far |
|---|---|---|
| 0 | 4 | 4 |
| 1 | 2 | 4(2 |
| 3 | 3 | 4(2(3 |
| 4 | 1 | 4(2(3)(1 |
| 2 | 6 | 4(2(3)(1))(6 |
| 5 | 5 | 4(2(3)(1))(6(5 |
Input: values = [1, 2], left = [-1, -1], right = [1, -1]
Output: "1()(2)"Step 1 has only a right child. The empty pair () marks the missing left child. Without it the line would equal the line of a plan with a left child.
Input: values = [], left = [], right = []
Output: ""An empty plan is an empty line.
0 ≤ length of values ≤ 2 × 10^5values, left and right have the same length.1 ≤ values[i] ≤ 10^9left and right form a binary tree rooted at node 0.A plan can be a chain of 200,000 steps, so a recursive function would nest 200,000 calls deep. Python stops such a function with a RecursionError, and Java and C++ risk a stack overflow. Use an explicit stack.
The longest text on a chain has 2,399,998 characters. Building it one node at a time, copying the whole text again at every node, would copy about 240,001,200,000 characters. Build a list of pieces and join it once.