FunctionRacerProblemsRace

Construct String from Binary Tree

EasyTreesPython, JavaScript, TypeScript, Java, C++

You are given the root of a binary tree. Turn the tree into a string using preorder. Write a node's value, then its left subtree wrapped in parentheses, then its right subtree wrapped in parentheses. Leave out the parentheses for a missing child, except when the left child is missing but the right child exists: then write () for the left. So [1,2,3] is "1(2)(3)", [1,2] is "1(2)", and [1,None,3] is "1()(3)". An empty tree gives "".

Trees appear in the tests in level order, with null for a missing child, like [3,9,20,null,null,15,7]. Each node is a TreeNode with .val, .left and .right; the class is already defined for you.

Example 1

root [1,2,3,4]
returns "1(2(4))(3)"

"1(2(4))(3)": 4 is the only child of 2, on its left.

Example 2

root [1,2,3,null,4]
returns "1(2()(4))(3)"

"1(2()(4))(3)": 2 has no left child but has a right one.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Trees problems