Java simple recursion


  • 14
     public String tree2str(TreeNode t) {
            StringBuilder sb = new StringBuilder();
            helper(sb,t);
            return sb.toString();
        }
        public void helper(StringBuilder sb,TreeNode t){
            if(t!=null){
                sb.append(t.val);
                if(t.left!=null||t.right!=null){
                    sb.append("(");
                    helper(sb,t.left);
                    sb.append(")");
                    if(t.right!=null){
                        sb.append("(");
                    helper(sb,t.right);
                    sb.append(")");
                    }
                }
            }
        }
    

  • 0
    S

    How are you including the case 1,2,null,3,4 ? in that case you will miss out on the two () brackets as per question's example 2. I have a similar solution but I didn't go ahead thinking I wont be able to surpass this test case


  • 0
    G

    @sushant_gupta The solution takes care of the case that you mentioned.

    Revisit these lines again :

    sb.append("(");
    helper(sb,t.left);
    sb.append(")");


  • 0

    The tricky part is the left subtree. If the left subtree is "" but the right is not, we need to append a empty ().

        public String tree2str(TreeNode t) {
          return helper(t);    
        }
        
        String helper(TreeNode t){
          if(t == null) return "";
          String l = helper(t.left);
          String r = helper(t.right);
          
          String res = "" + t.val;
          if(l == ""){
            if(r != "") res += "()";  
          } else {
            res += "(" + l + ")";  
          }
          
          if(r != "") res += "(" + r + ")"; 
          return res;
        }

Log in to reply
 

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