Ctrl K

Tree From Bracket Notation

Medium
A binary tree is written as the string text using this rule: first an integer, the node's value (it may be negative), then zero, one or two pairs of parentheses. Each pair holds a subtree written the same way. The first pair is always the left subtree and the second one is the right subtree. With only one pair, the node has just a left child. A pair may be empty: () means there is no subtree, which is how a node with only a right child is written, as in 5()(9). Build the tree and return its root. An empty string means an empty tree.
Example 1
text="7(3(1)(5))(-2(8))" → [7, 3, -2, 1, 5, 8]

The root is 7. The first bracket pair is the left subtree: 3 with children 1 and 5. The second is the right subtree: -2, which has a single pair, so 8 is its left child.

Example 2
text="12(4)" → [12, 4]

Only one bracket pair, so the root has just a left child.

Example 3
text="" → None

An empty string is an empty tree.

Constraints
  • 0 ≤ len(text) ≤ 3 · 10⁴
  • text consists of digits, (, ) and - and follows the rule above
  • |node value| ≤ 2³⁰
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree Into a Right Chain MediumChecking a Tree Record With Hash Marks MediumTree in Compact Brackets MediumSmallest Leaf-to-Root Word MediumPair Across Two Search Trees Medium
loading Python…
Input
text="7(3(1)(5))(-2(8))"
Expected
[7, 3, -2, 1, 5, 8]

Run checks the first 3 tests in your browser. Submit checks all 95 tests on the server, hidden ones included.