Easy to understand java solution


  • 19
    L
     public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();    
        helperS(root, sb);
        return sb.toString();
    }
    
    private void helperS(TreeNode node, StringBuilder sb){
        if(node == null){
            sb.append("null").append(",");
            return;
        }
        
        sb.append(node.val).append(",");
        
        helperS(node.left, sb);
        helperS(node.right, sb);
    }
    
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] vals  = data.split("[,]");
        int[]    index = new int[]{0};
        return helperD(vals, index);
    }
    
    private TreeNode helperD(String[] vals, int[] index){
        if(index[0] == vals.length){
            return null;
        }
        
        String visiting = vals[index[0]++];
        if(visiting.equals("null")){
            return null;
        }
        
        TreeNode node = new TreeNode(Integer.valueOf(visiting));
        node.left     = helperD(vals, index);
        node.right    = helperD(vals, index);
        
        return node;
    }

  • -2
    L
    This post is deleted!

  • 0
    L

    why not copy paste, try it yourself?


  • 0
    L

    I have written the code and try myself. After that, I just take a look at the discussed questions.


  • 0
    C

    The output is 1,2,null,null,3,null,null. But, there is no restriction about the serialized format, so, IMHO, as long as your deserialize() function can reconstruct the tree, it's acceptable to have output like this.


  • 0
    L

    ic, thank you so much. I ignore this sentence in the problem.


  • 0
    H

    very brilliant idea! very straightforward!


  • 0
    W
    This post is deleted!

  • 0
    M

    It does not deserialize correctly ..!!


  • 1
    A

    Why did you pass a unit length array instead of an integer value? Is there any advantage in doing this?


Log in to reply
 

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