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

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {
    
    private static final String NULL = "#";
    private static final String DELIMITER = ",";

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        serializeHelper(root, sb);
        return sb.toString().substring(0, sb.length()-1);
    }
    
    public void serializeHelper(TreeNode node, StringBuilder sb) {
        if (node == null) {
            sb.append(NULL).append(DELIMITER);
            return;
        }
        sb.append(node.val).append(DELIMITER);
        serializeHelper(node.left, sb);
        serializeHelper(node.right, sb);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] values = data.split(DELIMITER);
        return deserializeHelper(values, 0, values.length - 1);
    }
    
    public TreeNode deserializeHelper(String[] values, int start, int end) {
        if (start > end || NULL.equals(values[start])) {
            return null;
        }
        TreeNode node = new TreeNode(Integer.parseInt(values[start]));
        int i = start + 1;
        for(; i <= end; i++) {
            if (NULL.equals(values[i])){
                continue;
            }
            if (Integer.parseInt(values[i]) > node.val) {
                break;
            }
        }
        node.left = deserializeHelper(values, start+1, i-1);
        node.right = deserializeHelper(values, i, end);
        return node;
    }
}

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

 

上一篇:Mac环境下svn的使用


下一篇:LeetCode23_递归、双指针_有序链表构建BST