Construct String from Binary Tree


  • 0

    Click here to see the full article post


  • 0
    C

    How about this case [1,2,3,null,null,null,4] ?

    The expected answer is "1(2)(3()(4))", not sure why we omit the other two "()()".

    Thanks!


  • 0

    @Cornelius194968 For leaf nodes we only have to print the value of that node.


  • 0

    Good solution but a mirror mistake on iterative version: Since you use String Concatenation "+", every time you do a string concatenation, it declares a new string rather than add after the previous result string. It consumes lots of memory when the string grows. Should consider using StringBuilder/StringBuffer.


  • 0

    A Typo : Minor, not mirror...


  • 0

    @new2500 Yes you are right. I have replaced the string by StringBuilder. THanks.


  • 0
    P

    I have similar question as 'Cornelius194968'. For input [1,2,null,3,4], my answer is "1(2(3)(4))()", while the expected answer is "1(2(3)(4))". I think my answer is correct. Otherwise the input of [1,2,3,4] and [1,2,null,3,4] generates the same output. Obviously that's not correct.


  • 0
    L

    My answer is the same as approach #1 but I get this error:
    Line 15: TypeError: unsupported operand type(s) for +: 'int' and 'str'

    Any ideas why?


  • 0
    P

    /**

    • Definition for a binary tree node.
    • public class TreeNode {
    • int val;
      
    • TreeNode left;
      
    • TreeNode right;
      
    • TreeNode(int x) { val = x; }
      
    • }
      */
      class Solution {
      String answer = "";
      public String tree2str(TreeNode t) {
        if (t==null)return "";
        if (t.left == null && t.right==null){
            return t.val+"";
        }
        if (t.right==null){            
            return t.val+"("+tree2str(t.left)+")";                        
        }else  return t.val+"("+tree2str(t.left)+")("+tree2str(t.right)+")";                                          
    }
    

    }


  • 0
    P

    Case 4 is an important case in this question. After understanding that case you will understand what exactly the question means by mapping a binary tree to a string.

    The returned string can be used to rebuild the binary tree again.


Log in to reply
 

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