297. Serialize and Deserialize Binary Tree

307 查看

题目:
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

    1
   / \
  2   3
     / \
    4   5

as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

解答:

public class Codec {
    private String spliter = ",";
    //用一个特殊的符号来表示null的情况
    private String NN = "X";

    // Encodes a tree to a single string.
    public void BuildString(StringBuilder sb, TreeNode root) {
        if (root == null) {
            sb.append("X").append(spliter);
        } else {
            //这是按先序遍历来存root到string中去
            sb.append(root.val).append(spliter);
            BuildString(sb, root.left);
            BuildString(sb, root.right);
        }
    }
    
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        BuildString(sb, root);
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode BuildTree(Deque<String> nodes) {
        String node = nodes.remove();
        if (node.equals(NN)) {
            return null;
        } else {
            //Integer.valueOf("String");
            TreeNode root = new TreeNode(Integer.valueOf(node));
            root.left = BuildTree(nodes);
            root.right = BuildTree(nodes);
            return root;
        }
    }
    
    public TreeNode deserialize(String data) {
        //deque这里用linkedlist为interface,其包含了几乎所有resizable array
        Deque<String> nodes = new LinkedList<>();
        //这里还是挺多知识点的,String.split()后是一个String[], Arrays.asList()可以把数组变成list, nodes.addAll()则是把list加到nodes这个list的中去
        nodes.addAll(Arrays.asList(data.split(spliter)));
        return BuildTree(nodes);
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));