October 04, 2019

449. Serialize and Deserialize BST

449. Serialize and Deserialize BST

用的 BST 特性,不需要存空叶子的值。Time = O(n), Space = O(n)

Related Questions:
297. Serialize and Deserialize Binary Tree
428. Serialize and Deserialize N-ary Tree

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

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

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data.equals("")){
            return null; // pay attention to edge cases
        } 
        Deque<String> queue = new ArrayDeque<>(Arrays.asList(data.split(",")));
        return deserializeHelper(queue, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }
    
    private TreeNode deserializeHelper(Deque<String> queue, int minVal, int maxVal) {
        if (queue.isEmpty()) {
            return null;
        }
        int val = Integer.parseInt(queue.peek());
        if (val <= minVal || val >= maxVal) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(queue.poll()));
        root.left = deserializeHelper(queue, minVal, root.val);
        root.right = deserializeHelper(queue, root.val, maxVal);
        return root;
    }
}

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