问题:
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.与297题的区别
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
解决:
① 与相似,但是一般的树变成了BST,而且要求是as compact as possible。还是可以用preorder,还是需要分隔符,但是null就不需要保存了。deserialize部分要变得复杂,left的值总是小于root的值,right的值总是大于root的值,根据这个每次recursion的时候把左边的值都放到另一个queue里面,剩下的就是右边的值。
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));