Use StringBuilder:

public class Solution { public String tree2str(TreeNode t) { return dfs(t).toString(); } private StringBuilder dfs(TreeNode n) { if (n == null) { return new StringBuilder(); } // go right StringBuilder r = dfs(n.right); // go left StringBuilder l = dfs(n.left); if (r.length() != 0) { r.insert(0, "(").append(")"); } if (l.length() != 0) { l.insert(0, "(").append(")"); } if (l.length() == 0 && r.length() != 0) { l.append("()"); } // combine return l.append(r).insert(0, n.val); } }Construct String from Binary Tree