Java recursive solution using StringBuilder


  • 0
    S
    public class Solution {
        public String tree2str(TreeNode t) {
            if (t == null) {
                return new String("");
            }
            
            StringBuilder sb = new StringBuilder();
            tree2strHelper(t, sb);
            return sb.toString();
        }
        
        private void tree2strHelper(TreeNode t, StringBuilder sb) {
            if (t == null) {
                return;
            }
            
            sb.append(t.val);
            
            if (t.left == null && t.right == null) {
                return;
            }
            
            if (t.right != null) {
                sb.append('(');
                tree2strHelper(t.left, sb);
                sb.append(')');
                sb.append('(');
                tree2strHelper(t.right, sb);
                sb.append(')');
            } else {
                sb.append('(');
                tree2strHelper(t.left, sb);
                sb.append(')');
            }
        }
    }
    

Log in to reply
 

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