# Construct String from Binary Tree

The expected answer is "1(2)(3()(4))", not sure why we omit the other two "()()".

Thanks!

• @Cornelius194968 For leaf nodes we only have to print the value of that node.

• Good solution but a mirror mistake on iterative version: Since you use String Concatenation "+", every time you do a string concatenation, it declares a new string rather than add after the previous result string. It consumes lots of memory when the string grows. Should consider using StringBuilder/StringBuffer.

• A Typo : Minor, not mirror...

• @new2500 Yes you are right. I have replaced the string by StringBuilder. THanks.

• I have similar question as 'Cornelius194968'. For input [1,2,null,3,4], my answer is "1(2(3)(4))()", while the expected answer is "1(2(3)(4))". I think my answer is correct. Otherwise the input of [1,2,3,4] and [1,2,null,3,4] generates the same output. Obviously that's not correct.

• My answer is the same as approach #1 but I get this error:
Line 15: TypeError: unsupported operand type(s) for +: 'int' and 'str'

Any ideas why?

• /**

• Definition for a binary tree node.
• public class TreeNode {
• ``````int val;
``````
• ``````TreeNode left;
``````
• ``````TreeNode right;
``````
• ``````TreeNode(int x) { val = x; }
``````
• }
*/
class Solution {
public String tree2str(TreeNode t) {
``````    if (t==null)return "";
if (t.left == null && t.right==null){
return t.val+"";
}
if (t.right==null){
return t.val+"("+tree2str(t.left)+")";
}else  return t.val+"("+tree2str(t.left)+")("+tree2str(t.right)+")";
}
``````

}

• Case 4 is an important case in this question. After understanding that case you will understand what exactly the question means by mapping a binary tree to a string.

The returned string can be used to rebuild the binary tree again.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.