Java O(n) solution using StringBuilder


  • 0
    K
    public class Solution {
        public String tree2str(TreeNode t) {
            if(t == null) return "";
            StringBuilder sb = new StringBuilder();
            preorder(t, sb);
            return sb.toString();
        }
        
        private void preorder(TreeNode root, StringBuilder sb) {
            if(root == null) return;
            
            sb.append(root.val);
            
            if(root.left != null || root.right != null) {
                sb.append("(");
                preorder(root.left, sb);
                sb.append(")");
            }
            if(root.right != null) {
                sb.append("(");
                preorder(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.