7.Binary Tree Serialization

1.Description(Medium)

Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.

Notice

There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output ofserializeas the input ofdeserialize, it won't check the result of serialize.

Example

An example of testdata: Binary tree{3,9,20,#,#,15,7}, denote the following structure:

  3
 / \
9  20
  /  \
 15   7

Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.

You can use other method to do serializaiton and deserialization.

2.Code

public String serialize(TreeNode root) {
        if(root==null){
            return "{}";
        }
        StringBuilder sb=new StringBuilder();
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        queue.offer(root);
        sb.append("{");
        while(!queue.isEmpty()){
            TreeNode current=queue.poll();
            if(current!=null){
                sb.append(String.valueOf(current.val)+",");
                //if left or right is null then push a null in it.
                queue.offer(current.left);
                queue.offer(current.right);  
            }
            else{
                sb.append("#,");
            }

        }
        //delete the last comma
        sb.deleteCharAt(sb.length()-1);
        sb.append("}");
        return sb.toString();       
    }

    /**
     * This method will be invoked second, the argument data is what exactly
     * you serialized at method "serialize", that means the data is not given by
     * system, it's given by your own serialize method. So the format of data is
     * designed by yourself, and deserialize it here as you serialize it in 
     * "serialize" method.
     */
    public TreeNode deserialize(String data) {
         if(data.equals("{}")){
            return null;
        }
        //delete the {},and for substring,begin is inclusive,end is exclusive
        String str=data.substring(1,data.length()-1);
        //Get the array of node
        String[] arr=str.split(",");
        //Get the first element as root;
        TreeNode root=new TreeNode(Integer.parseInt(arr[0]));
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        int index=1;//coz arr[0] has been in the queue
        queue.offer(root);

        while(!queue.isEmpty()){
            TreeNode current=queue.poll();
            if(current==null){
                continue;
            }

            if(!arr[index].equals("#")){
                TreeNode left=new TreeNode(Integer.parseInt(arr[index]));
                queue.offer(left);
                current.left=left;
            }else{
                //没有也要offer一个Null
                queue.offer(null);
                current.left=null;
            }
            index++;//每次检查完一个元素后就index++;

            if(!arr[index].equals("#")){
                TreeNode right=new TreeNode(Integer.parseInt(arr[index]));
                queue.offer(right);
                current.right=right;
            }else{
                queue.offer(null);
                current.right=null;
            }
            index++;
        }
        return root;             
    }

Last updated