1. 程式人生 > >難1 297. Serialize and Deserialize Binary Tree

難1 297. Serialize and Deserialize Binary Tree

ros yourself span there slist connect truct size com

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 = {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