序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。
请设计一个算法来实现二叉树的序列化与反序列化。这里不限定你的序列 / 反序列化算法执行逻辑,你只需要保证一个二叉树可以被序列化为一个字符串并且将这个字符串反序列化为原始的树结构。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode 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;
}
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
StringBuilder s = new StringBuilder();
s.append(root.val + ",");
while (!q.isEmpty()) {
TreeNode t = q.poll();
if (t.left != null) {
q.offer(t.left);
s.append(t.left.val + ",");
}else {
s.append("null" + ",");
}
if (t.right != null) {
q.offer(t.right);
s.append(t.right.val + ",");
}else {
s.append("null" + ",");
}
}
s.deleteCharAt(s.length()-1);
String str = new String(s);
return str;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null || data.length() == 0) {
return null;
}
String[] str = data.split(",");
TreeNode root = new TreeNode(Integer.valueOf(str[0]));
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
int index = 1;
while (!q.isEmpty()) {
TreeNode t = q.poll();
if (!str[index].equals("null")) {
TreeNode left = new TreeNode(Integer.valueOf(str[index]));
t.left = left;
q.offer(left);
}
index++;
if (!str[index].equals("null")) {
TreeNode right = new TreeNode(Integer.valueOf(str[index]));
t.right = right;
q.offer(right);
}
index++;
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));