Java recursion StringBuilder


  • 2
    public static String tree2str(TreeNode t) {
            if(t == null) return "";
            return tree2str1(t).toString();
        }
    
        public static StringBuilder tree2str1(TreeNode t) {
            if(t == null) return null;
    
            StringBuilder sb = new StringBuilder();
            sb.append(t.val);
    
            StringBuilder left = tree2str1(t.left);
            StringBuilder right = tree2str1(t.right);
    
            if(right == null && left == null) return sb;
            sb.append("(").append(left == null ? "" : left).append(")");
            if(right != null) sb.append("(").append(right).append(")");
            return sb;
        }
    
    

Log in to reply
 

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