天天看点

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));
           

继续阅读