Problem 606 · LeetCode 606(opens in a new tab)
Construct String from Binary Tree
MediumDepth-first search
You are given the root of a binary tree. Turn it into a string by a preorder walk: write each node's value, then its left subtree inside round brackets, then its right subtree inside round brackets.
Leave out every pair of brackets that would be empty, with one exception. When the left child is missing while the right one exists, keep an empty () for the missing left side, so the string still shows which side the child is on. Return the finished string.
Example 1
Input: root = [3, 9, 4, null, 7] Output: "3(9()(7))(4)" Why: 9 has only a right child, so its empty left pair stays
2 more examples and the constraints
Example 2
Input: root = [6, 4, 1, 3] Output: "6(4(3))(1)" Why: 4 has only a left child; no empty pair is needed after it
Example 3
Input: root = [7, null, -9] Output: "7()(-9)" Why: a lone right child keeps the "()" before it
Constraints
- 1 ≤ number of nodes ≤ 10,000
- −1,000 ≤ Node.val ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with string joinsO(n²) worst
- One preorder pass with a stackO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 10,000-node chain | Verdict |
|---|---|---|---|
| Recursion with string joins | O(n²) worst | Short; recopies strings on deep trees | |
| One preorder pass with a stack | O(n) | Best; each character written once |
n = number of nodes. On a balanced tree the recursive version is only O(n log n).
Edge cases to test
- Single node. The answer is just its value, with no brackets.
- Only a right child. Write
()before it: 7 with right child −9 gives "7()(-9)". - Only a left child. No empty pair after it: 4 with left child 3 gives "4(3)".
- Negative values. The minus sign is part of the value: "(-9)".
- A long chain. 10,000 nodes in a line: avoid copying strings at every level and deep recursion.
Common mistakes
- Dropping the
()for a missing left child when a right child exists. - Writing
()for a missing right child, which the rules never ask for. - Forgetting to strip the brackets around the root in the stack version.
How to talk through it
- 1Clarify. Which empty pairs are kept? Only the left one, and only when a right child exists.
- 2Spot the walk. Value, then left, then right is a preorder traversal.
- 3Give the recursion. Return value + (left) + (right); mention the string copying on a chain.
- 4One buffer. Open each node on its first visit and close it on its second, with an explicit stack.
- 5Test out loud. Run one node, a lone right child, a lone left child and a negative value.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?