Java stringbuilder recursive solution


  • 0
    H
    public String tree2str(TreeNode t) {
            if(t==null) return "";
            StringBuilder sb = new StringBuilder();
            helper(sb , t);
            if(sb.length()>2){
                sb.deleteCharAt(0);
                sb.deleteCharAt(sb.length()-1);
            }
            return sb.toString();
        }
    
        private void helper(StringBuilder sb, TreeNode root){
            // root
            sb.append("(");
            sb.append(root.val);
            
            // left
            if(root.left != null)
                helper(sb, root.left);
            else if(root.right!=null)
                sb.append("()");
    
            // right
            if(root.right != null)
                helper(sb, root.right);
    
            sb.append(")");
        }
    

Log in to reply
 

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