首页 > 代码库 > 难1 297. Serialize and Deserialize Binary Tree

难1 297. Serialize and Deserialize Binary Tree

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.

ote最高的PreOrder Traversal (Recursion)做法

本题别人用了双向队列 Deque, 注意23-24行,写的非常好

另外再注意一下29行的语法,nodes就是指向这个linkedlist的,所以linkedlist再怎么删,nodes始终指向linkedlist,而不是linkedlist的head,所以33-34行可以直接用nodes,而不需要考虑是不是要指向head的下一个

正是因为null 的存在, 才使得preorder 一个就能构建树, 因为知道了preorder在构建String 时什么时候返回的.

public class Codec {
    private static final String spliter = ",";
    private static final String NN = "X";

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        buildString(root, sb);
        return sb.toString();
    }

    private void buildString(TreeNode node, StringBuilder sb) {
        if (node == null) {
            sb.append(NN).append(spliter);
        } else {
            sb.append(node.val).append(spliter);
            buildString(node.left, sb);
            buildString(node.right,sb);
        }
    }
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        Deque<String> nodes = new LinkedList<>();
        nodes.addAll(Arrays.asList(data.split(spliter)));
        return buildTree(nodes);
    }
    
    private TreeNode buildTree(Deque<String> nodes) {
        String val = nodes.remove();
        if (val.equals(NN)) return null;
        else {
            TreeNode node = new TreeNode(Integer.valueOf(val));
            node.left = buildTree(nodes);
            node.right = buildTree(nodes);
            return node;
        }
    }
}
Deque<String> nodes = new LinkedList<>();
nodes.addAll(Arrays.asList(data.split(spliter)));

int[] data = http://www.mamicode.com/{1,2,3,4,5};

List list = Arrays.asList(data);

Follow Up:

如果已经知道这个Binary Tree的size为T, 怎么估计输出链表size?

答案是 2*T+1,    (假设tree perfect and complete, leaf node层有大概一半的node数,比之前所有层的node数之和还要多一,那么,最后一层node每个再派生两个“#”, 个数就会有T+1个,所以总共有2*T+1个)

难1 297. Serialize and Deserialize Binary Tree