Ctrl K

Tree in Compact Brackets

Medium
You get the root root of a binary tree. Write the tree as a single string by these rules (visiting node, then left subtree, then right subtree): - a node is written as its value; - if a node has children, its value is followed by the left subtree in brackets and then the right subtree in brackets; - empty bracket pairs () are left out, with one exception: when the left child is missing but the right one exists, the empty pair () must stay in the left child's place, otherwise the right child could not be told apart from a left one. So a leaf gets no brackets at all, and a node with only a left child gets a single pair.
Example 1
root=tree_node([7, -2, 5, None, None, 1]) → '7(-2)(5(1))'

-2 has no children, so it is written as just -2. 5 has only a left child, so it becomes 5(1) with no empty brackets on the right. Result: 7(-2)(5(1)).

Example 2
root=tree_node([4, None, 9, 8]) → '4()(9(8))'

4 has no left child but does have a right one, so an empty pair () is required: 4()(9(8)).

Example 3
root=tree_node([3]) → '3'
Constraints
  • The tree has between 1 and 10⁴ nodes
  • -1000 ≤ node value ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTree From Bracket Notation MediumSmallest Leaf-to-Root Word MediumDirections Through a Tree MediumRoutes from Root to Leaves EasyTree From a Dashed Preorder Record Hard
loading Python…
Input
root=tree_node([7, -2, 5, None, None, 1])
Expected
'7(-2)(5(1))'

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