天天看點

Serialize and Deserialize BST

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

The encoded string should be as compact as possible.

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

思路:這題跟 serilaize BT不同的地方是,這裡是BST,是有左右的大小資訊的,是以就不需要serialize null和empty的節點,是以隻用Interger.MIN_VALUE Integer.MAX_VALUE來判斷範圍就行了。超出範圍,return null;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {

    private String DELIMITER = ",";
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        dfs(root, sb);
        return sb.toString();
    }
    
    private void dfs(TreeNode root, StringBuilder sb) {
        if(root == null) {
            return;
        }
        sb.append(root.val).append(DELIMITER);
        dfs(root.left, sb);
        dfs(root.right, sb);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data.isEmpty()) {
            return null;
        }
        String[] splits = data.split(DELIMITER);
        Queue<String> queue = new LinkedList<String>();
        for(String split: splits) {
            queue.offer(split);
        }
        return buildTree(queue, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }
    
    private TreeNode buildTree(Queue<String> queue, int lower, int upper) {
        if(queue.isEmpty()) {
            return null;
        }
        // 注意這裡首先要peek一下,看是否是在範圍,不能盲目的poll;
        String head = queue.peek();
        int val = Integer.parseInt(head);
        if(val < lower || val > upper) {
            return null;
        }
        // 如果滿足範圍要求了,才poll出來,build node;否則是下一個區間的node;
        queue.poll();
        TreeNode root = new TreeNode(val);
        root.left = buildTree(queue, lower, val);
        root.right = buildTree(queue, val, upper);
        return root;
    }
}

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

繼續閱讀