AC Java solution


  • 0
    class Solution {
        public String tree2str(TreeNode t) {
            StringBuilder result = new StringBuilder();
            helper(result, t);
            return result.toString();
        }
        
        private void helper(StringBuilder result, TreeNode t) {
            if(t == null) 
                return ;
            result.append("" + t.val);
            if(t.left == null && t.right == null)
                return;
            result.append("(");
            helper(result, t.left);
            result.append(")");
            if(t.right == null) 
                return;
            result.append("(");
            helper(result, t.right);
            result.append(")");
        }
    }
    

Log in to reply
 

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