Java recursive 16ms


  • 0
    U
    public class Solution {
        public String tree2str(TreeNode root) {
            StringBuilder sb = new StringBuilder();
            helper(root, sb);
            return sb.toString();
        }
        
        private static void helper(TreeNode root, StringBuilder sb) {
            if (root == null) {
                return;
            }
            sb.append(String.valueOf(root.val));
            if (root.left == null && root.right == null) {
                return;
            }
            if (root.left == null) {
                sb.append("()");
            } else {
                sb.append("(");
                helper(root.left, sb);
                sb.append(")");
            }
            if (root.right != null) {
                sb.append("(");
                helper(root.right, sb);
                sb.append(")");
            }
    
        }
    }
    
    

Log in to reply
 

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