序列化和反序列化二叉搜索樹 Serialize and Deserialize BST

問題:app

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

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

The encoded string should be as compact as possible.與297題的區別this

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.spa

解決:.net

①  與Serialize and Deserialize Binary Tree類似,可是通常的樹變成了BST,並且要求是as compact as possible。仍是能夠用preorder,仍是須要分隔符,可是null就不須要保存了。deserialize部分要變得複雜,left的值老是小於root的值,right的值老是大於root的值,根據這個每次recursion的時候把左邊的值都放到另外一個queue裏面,剩下的就是右邊的值。rest

public class Codec { //17ms
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) return "";
        StringBuilder encodedStr = new StringBuilder();
        encode(root,encodedStr);
        return encodedStr.substring(1).toString();
    }
    public void encode(TreeNode root,StringBuilder sb){
        if (root == null) return;
        sb.append(",").append(root.val);
        encode(root.left,sb);
        encode(root.right,sb);
    }
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data.length() == 0) return null;
        Queue<Integer> queue = new LinkedList<>();
        for (String s : data.split(",")){
            queue.offer(Integer.valueOf(s));
        }
        return decode(queue);
    }
    public TreeNode decode(Queue<Integer> queue){
        if (queue.isEmpty()) return null;
        int cur = queue.poll();
        TreeNode root = new TreeNode(cur);
        Queue<Integer> left = new LinkedList<>();
        while(! queue.isEmpty() && queue.peek() < cur){
            left.offer(queue.poll());
        }
        root.left = decode(left);
        root.right = decode(queue);
        return root;
    }
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));code

相關文章
相關標籤/搜索