Serialize and Deserialize BST

Problem

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.

Solution

public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if (root == null) return "";
        StringBuilder sb = new StringBuilder();
        Stack<TreeNode> s = new Stack<>();
        s.push(root);
        while (!s.isEmpty()) {
            TreeNode node = s.pop();
            sb.append(node.val).append(",");
            if (node.right != null) s.push(node.right);
            if (node.left != null) s.push(node.left);
        }
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data.length() == 0) return null;
        String[] strs = data.split(",");
        Queue<Integer> q = new LinkedList<>();
        for (String str : strs) q.offer(Integer.parseInt(str));
        return getNode(q);
    }

    private TreeNode getNode(Queue<Integer> q) {
        if (q.isEmpty()) return null;
        TreeNode root = new TreeNode(q.poll());
        Queue<Integer> leftQ = new LinkedList<>();
        while (!q.isEmpty() && q.peek() < root.val) leftQ.offer(q.poll());
        root.left = getNode(leftQ);
        root.right = getNode(q);
        return root;
    }

}

Analysis

In serialize() method, we use Stack and StringBuilder to get values in the inorder traversal
Then in deserialize() method, we convert the String data to Queue and use helper method
In the helper method getNode(), we construct new TreeNode with q.pop() as its value
Then we get the values smaller than root.val and recursively set root.left and root.right
Smart recursion use, you have to say.

results matching ""

    No results matching ""