Java BEATS 85% - DFS - STRINGBUILDER!


  • 0
    J

    Someone refactor it and make it one line =(

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

Log in to reply
 

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