1642. Bracket Text to Tree
A tree is written as text. A node is its integer value (with a leading minus sign when negative) followed by zero, one or two groups in parentheses, and each group holds the text of a whole subtree. With two groups, the first is the left child and the second is the right child; with exactly one group, it is the left child. A lone right child is never written, so text like 7()(3) does not occur.
For example, 9(-2(4)(1))(7(5)) describes a root 9 whose left child -2 has two leaf children 4 and 1, and whose right child 7 has a single left child 5. Given the string s, build the tree and return its root. The string is always valid. Aim for O(|s|) time and space by parsing with an explicit stack of open nodes.
Example 1
- Input:
- s = "9(-2(4)(1))(7(5))"
- Output:
- [9,-2,7,4,1,5]
- Explanation:
Root 9 has left subtree -2(4)(1) and right subtree 7(5); level order lists 9, -2, 7, 4, 1, 5.
Example 2
- Input:
- s = "6"
- Output:
- [6]
- Explanation:
A bare number is a single-node tree.
Example 3
- Input:
- s = "-3(0)"
- Output:
- [-3,0]
- Explanation:
One group means a single left child, so -3 has left child 0.
Constraints
1 ≤ s.length ≤ 3000
at most 500 nodes
values in [-1000, 1000]
s is valid
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)