7. Serialize and Deserialize Binary Tree

7. Serialize and Deserialize Binary Tree

Description

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'.

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.

Solution

import java.util.*;
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * 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) {
        // write your code here
        if(root == null) return "{}";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{");
        Queue<TreeNode> treeNodeQueue = new LinkedList<>();
        treeNodeQueue.offer(root);
        int temDeep = 0;
        int deep = getMaxTreeDeep(root)-1;
        while(!treeNodeQueue.isEmpty()){
            for(int i=0;i<Math.pow(2,temDeep);i++) {
                TreeNode node = treeNodeQueue.poll();
                if (node == null) {
                    stringBuilder.append("#,");
                    treeNodeQueue.offer(null);
                    treeNodeQueue.offer(null);
                }
                else {
                    stringBuilder.append(node.val + ",");
                    treeNodeQueue.offer(node.left);
                    treeNodeQueue.offer(node.right);
                }
            }
            if(temDeep < deep) temDeep++;
            else break;
        }
        stringBuilder.deleteCharAt(stringBuilder.length()-1);
        stringBuilder.append("}");
        return stringBuilder.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) {
        // write your code here
        if(data.equals("{}")) return null;
        data = data.substring(1,data.length()-1);
        String[] datas = data.split(",");
        if(datas.length<=0) return null;
        ArrayList<TreeNode> nodes = new ArrayList<>();
        int index = -1;
        for(int i=0;i<datas.length;i++){
            if(datas[i].equals("#")){
                nodes.add(null);
            }else{
                TreeNode leftNode = new TreeNode(Integer.parseInt(datas[i]));
                nodes.add(leftNode);
                if(index>=0){
                    if(nodes.get(index)!=null) {
                        nodes.get(index).left = leftNode;
                    }
                }else{
                    index++;
                    continue;
                }
            }
            i++;
            if(datas[i].equals("#")){
                nodes.add(null);
            }else{
                TreeNode rightNode = new TreeNode(Integer.parseInt(datas[i]));
                nodes.add(rightNode);
                if(index>=0){
                    if(nodes.get(index)!=null) {
                        nodes.get(index).right = rightNode;
                    }
                }
            }
            index++;
        }
        return nodes.get(0);
    }

    private int getMaxTreeDeep(TreeNode root){
        if(root == null) return 0;
        int ml = getMaxTreeDeep(root.left);
        int mr = getMaxTreeDeep(root.right);
        return Math.max(ml,mr)+1;
    }
}

猜你喜欢

转载自blog.csdn.net/foradawn/article/details/79943830