Construct String from Binary Tree (LeetCode 606): Solution and Explanation
Turn a binary tree into a string: each value is followed by its left child's string in parentheses and then its right child's string in parentheses. Empty pairs are dropped, except the "()" that stands for a missing left child when a right child exists.
Intuition
The string is a preorder listing: a node comes before both of its subtrees, and each subtree is wrapped in its own pair of parentheses.
The only real question at each node is which pairs to write. A pair for the right child is needed only when there is a right child, because nothing comes after it.
The left pair is different. If a node has a right child but no left child, dropping the left pair would make the right child look like a left child. So the left pair is written whenever the node has any child at all, even if it ends up as "()".
Approach: Preorder walk with a string builder
- Write the node's value.
- If the node has a left or a right child, write "(", recurse into the left child if there is one, and write ")".
- If the node has a right child, write "(", recurse into it, and write ")".
- A leaf writes only its value.
- Join all the pieces once at the end and return the string.
Step-by-step example
root = [1,2,3,4]
- Write 1. It has children, so open its left slot: "1(".
- Write 2. It has a left child, so open: "1(2(". Write the leaf 4 and close: "1(2(4)".
- Node 2 has no right child, so no right pair. Close 1's left slot: "1(2(4))".
- Node 1 has a right child 3: "1(2(4))(3)". 3 is a leaf, so nothing more.
- Return "1(2(4))(3)".
Code: Python, Java, C++
1class Solution:
2 def tree2str(self, root: Optional[TreeNode]) -> str:
3 out = []
4
5 def walk(node):
6 out.append(str(node.val))
7 if node.left or node.right:
8 out.append('(')
9 if node.left:
10 walk(node.left)
11 out.append(')')
12 if node.right:
13 out.append('(')
14 walk(node.right)
15 out.append(')')
16
17 walk(root)
18 return ''.join(out)1class Solution {
2 public String tree2str(TreeNode root) {
3 StringBuilder sb = new StringBuilder();
4 walk(root, sb);
5 return sb.toString();
6 }
7
8 private void walk(TreeNode node, StringBuilder sb) {
9 sb.append(node.val);
10 if (node.left != null || node.right != null) {
11 sb.append('(');
12 if (node.left != null) walk(node.left, sb);
13 sb.append(')');
14 }
15 if (node.right != null) {
16 sb.append('(');
17 walk(node.right, sb);
18 sb.append(')');
19 }
20 }
21}1class Solution {
2 void walk(TreeNode* node, string& out) {
3 out += to_string(node->val);
4 if (node->left || node->right) {
5 out += '(';
6 if (node->left) walk(node->left, out);
7 out += ')';
8 }
9 if (node->right) {
10 out += '(';
11 walk(node->right, out);
12 out += ')';
13 }
14 }
15
16public:
17 string tree2str(TreeNode* root) {
18 string out;
19 walk(root, out);
20 return out;
21 }
22};Time and space complexity
O(n)
Every node is visited once and appends at most five pieces. Joining at the end is linear in the output length.
O(n)
The output holds every value and up to two pairs of parentheses per node. The recursion adds O(h) on top.
Other approaches
Return strings from each call (time O(n^2) worst case, space O(n^2) worst case)
Have each call return its subtree's string and concatenate. Short to write, but repeated concatenation copies strings and can cost O(n^2) on a deep tree.
Iterative preorder with a stack (time O(n), space O(n))
Push nodes with a visited flag, write the value and "(" on the first visit and ")" on the second. Avoids recursion depth limits on a 10^4-node chain.
Common mistakes
- Dropping the "()" for a missing left child when a right child exists. That makes the tree ambiguous and gives the wrong answer.
- Writing "()" for a missing right child. Nothing follows it, so it is never needed.
- Building the result with repeated string concatenation in a language where strings are immutable, which turns a linear walk quadratic.
- Forgetting negative values: the minus sign is part of the number, so convert the whole integer to text.
Frequently asked questions
Why is "()" kept only before a right child?
Without it, a string like "1(2)" could mean 2 is the left child or the right child. The rule says a single group is always the left child, so a lone right child needs the empty left group in front of it.
Can the original tree be rebuilt from this string?
Yes. That is the point of keeping the one kind of empty pair: the mapping from trees to strings is one to one, and LeetCode 536 asks for the reverse parse.
Does recursion depth matter here?
A tree with 10^4 nodes in a single chain recurses 10^4 levels deep. Python's default limit is 1000, so on such inputs an iterative version or a raised recursion limit is safer.