7.Binary Tree Serialization

1.Desciption(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

serialize: 树变序列:用一个stringbuilder ,每次append进去元素和逗号,最后再把最后一个逗号去掉。

deserialize序列变树,开始先用substring和split把{}和,去掉,是他们变成一个数组,再进入队列,注意没poll一个元素要先判断是不是空再进行下面的操作。用一个Index来控制读取数组的哪个值。

 /**
     * This method will be invoked first, you should design your own algorithm 
     * to serialize a binary tree which denote by a root node to a string which
     * can be easily deserialized by your own "deserialize" method later.
     */
    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)+",");
            //注意要在这里offer left right因为如果是空就没有后续了。
            //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();
            //这里一定要判断是不是null因为offer进来好多null
            if(current==null){
                continue;
            }
            //判断元素要用equals不要用arr[i]==""
            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