Medium
Serialization is 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 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.
Example 1:
Input: root = [2,1,3]
Output: [2,1,3]
Example 2:
Input: root = []
Output: []
Constraints:
[0, 104]
.0 <= Node.val <= 104
import com_github_leetcode.TreeNode;
/*
* 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 char SPLIT = (char) 0;
private static final int MIN = 1;
private int cur;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
serializeDfs(root, sb);
return sb.toString();
}
private void serializeDfs(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append(SPLIT);
return;
}
sb.append((char) (root.val + MIN));
serializeDfs(root.left, sb);
serializeDfs(root.right, sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
cur = 0;
return deserializeDFS(data.toCharArray());
}
private TreeNode deserializeDFS(char[] data) {
if (data[cur] == SPLIT) {
cur++;
return null;
}
TreeNode node = new TreeNode(data[cur++] - MIN);
node.left = deserializeDFS(data);
node.right = deserializeDFS(data);
return node;
}
}
// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// String tree = ser.serialize(root);
// TreeNode ans = deser.deserialize(tree);
// return ans;