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
as "[1,2,3,null,null,4,5]"
, just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.
Solution
BFS
Level order traversal,形式跟leetcode oj的完全相同,即null尽量省略。
/**
* 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 "";
}
StringBuilder sb = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
Queue<TreeNode> nextLevel = new LinkedList<>();
boolean nextLevelExists = false; // whether there's non-null node in next level
while (size-- > 0) {
TreeNode node = queue.poll();
sb.append(sb.length() > 0 ? "," : "");
if (node == null) {
sb.append("null");
continue;
}
sb.append(node.val);
nextLevel.offer(node.left);
nextLevel.offer(node.right);
nextLevelExists |= node.left != null || node.right != null;
}
if (nextLevelExists) { // in order to omit extra nulls in the end
queue = nextLevel;
}
}
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data == null || data.isEmpty()) {
return null;
}
String[] tokens = data.split(",");
TreeNode root = new TreeNode(Integer.parseInt(tokens[0]));
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
for (int i = 1; i < tokens.length; ++i) {
TreeNode node = queue.poll();
if (!"null".equals(tokens[i])) {
TreeNode left = new TreeNode(Integer.parseInt(tokens[i]));
node.left = left;
queue.offer(left);
}
if (!"null".equals(tokens[++i])) {
TreeNode right = new TreeNode(Integer.parseInt(tokens[i]));
node.right = right;
queue.offer(right);
}
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
DFS
利用preorder traversal。deserialize的时候将tokens存入queue是个不错的想法,这样每次从queue取出一个string来就行,就不需要保存当前处理到的index了。
/**
* 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) {
StringBuilder sb = new StringBuilder();
dfsSerialize(root, sb);
return sb.toString();
}
private void dfsSerialize(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append("null,");
return;
}
sb.append(root.val).append(",");
dfsSerialize(root.left, sb);
dfsSerialize(root.right, sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
Queue<String> queue = new LinkedList<>();
queue.addAll(Arrays.asList(data.split(",")));
return dfsDeserialize(queue);
}
private TreeNode dfsDeserialize(Queue<String> queue) {
String s = queue.poll();
if ("null".equals(s)) {
return null;
}
TreeNode node = new TreeNode(Integer.parseInt(s));
node.left = dfsDeserialize(queue);
node.right = dfsDeserialize(queue);
return node;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));