问题:app
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.less
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.ui
The encoded string should be as compact as possible.与297题的区别this
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.spa
解决:.net
① 与Serialize and Deserialize Binary Tree类似,可是通常的树变成了BST,并且要求是as compact as possible。仍是能够用preorder,仍是须要分隔符,可是null就不须要保存了。deserialize部分要变得复杂,left的值老是小于root的值,right的值老是大于root的值,根据这个每次recursion的时候把左边的值都放到另外一个queue里面,剩下的就是右边的值。rest
public class Codec { //17ms
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) return "";
StringBuilder encodedStr = new StringBuilder();
encode(root,encodedStr);
return encodedStr.substring(1).toString();
}
public void encode(TreeNode root,StringBuilder sb){
if (root == null) return;
sb.append(",").append(root.val);
encode(root.left,sb);
encode(root.right,sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.length() == 0) return null;
Queue<Integer> queue = new LinkedList<>();
for (String s : data.split(",")){
queue.offer(Integer.valueOf(s));
}
return decode(queue);
}
public TreeNode decode(Queue<Integer> queue){
if (queue.isEmpty()) return null;
int cur = queue.poll();
TreeNode root = new TreeNode(cur);
Queue<Integer> left = new LinkedList<>();
while(! queue.isEmpty() && queue.peek() < cur){
left.offer(queue.poll());
}
root.left = decode(left);
root.right = decode(queue);
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));code