My 2 Java solutions by using StringBuilder


  • 0

    First:

    public String tree2str(TreeNode t) {
        if (t == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(t.val);
        if (t.left != null || t.right != null) {
            sb.append("(");
            sb.append(tree2str(t.left));
            sb.append(")");
            if (t.right != null) {
                sb.append("(");
                sb.append(tree2str(t.right));
                sb.append(")");
            }
        }
    
        return sb.toString();
    }
    

    Second:

    StringBuilder sb = new StringBuilder();
    
    public String tree2str(TreeNode t) {
        concat(t);
        return sb.toString();
    }
    
    public void concat(TreeNode t) {
        if (t == null) {
            return;
        }
        sb.append(t.val);
        if (t.left != null || t.right != null) {
            sb.append("(");
            concat(t.left);
            sb.append(")");
            if (t.right != null) {
                sb.append("(");
                concat(t.right);
                sb.append(")");
            }
        }
    }

Log in to reply
 

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