Java solution with 14ms


  • 0
    public String tree2str(TreeNode t) {
        StringBuilder sb = new StringBuilder();
        tree2str(sb,t);
        return sb.toString();
    }
        
    private void tree2str(StringBuilder sb,TreeNode t){
        if (t == null) return;
        sb.append(t.val);
        if (t.left == null && t.right != null) {
            sb.append("()");
            sb.append("(");
            tree2str(sb, t.right);
            sb.append(")");
        } else {
            if (t.left != null) {
                sb.append("(");
                tree2str(sb, t.left);
                sb.append(")");
            }
            if (t.right != null) {
                sb.append("(");
                tree2str(sb, t.right);
                sb.append(")");
            }
        }
    }
    

Log in to reply
 

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