Description:
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 tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.
For example, you may serialize the following tree
MLE Solution
<span style="font-size:18px;">import java.util.LinkedList;
/**
* Definition for a binary tree node. public class TreeNode { int val; TreeNode
* left; TreeNode right; TreeNode(int x) { val = x; } }
*/
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) {
val = x;
}
}
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null)
return null;
StringBuilder ans = new StringBuilder();
TreeNode node;
int count = 0;
int currentCount = 0;
LinkedList<TreeNode> nodeList = new LinkedList<TreeNode>();
LinkedList<Integer> countList = new LinkedList<Integer>();
nodeList.add(root);
countList.add(0);
while (!nodeList.isEmpty()) {
node = nodeList.poll();
count = countList.poll();
for (int i = currentCount + 1; i < count; i++)
ans.append(",null");
currentCount = count;
ans.append(",");
ans.append(node.val);
if (node.left != null) {
nodeList.add(node.left);
countList.add(count * 2 + 1);
}
if (node.right != null) {
nodeList.add(node.right);
countList.add(count * 2 + 2);
}
}
return ans.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null)
return null;
data = data.substring(1, data.length());
String[] list = data.split(",");
int len = list.length;
if (len == 0)
return null;
TreeNode nodeList[] = new TreeNode[len];
for (int i = 0; i < len; i++)
if (!list[i].equals("null"))
nodeList[i] = new TreeNode(Integer.parseInt(list[i]));
for (int i = 0; i < len; i++) {
if (nodeList[i] == null)
continue;
if (i * 2 + 1 < len && nodeList[i * 2 + 1] != null) {
nodeList[i].left = nodeList[i * 2 + 1];
}
if (i * 2 + 2 < len && nodeList[i * 2 + 2] != null) {
nodeList[i].right = nodeList[i * 2 + 2];
}
}
return nodeList[0];
}
public static void main(String[] args) {
Codec c = new Codec();
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
t1.right = t2;
TreeNode t3 = new TreeNode(3);
t2.left = t3;
String se = c.serialize(t1);
System.out.println(se);
TreeNode n = c.deserialize(se);
System.out.println(n.val);
}
}</span>