Easy to read Java recursion solution, beat 90%+


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

Log in to reply
 

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