297. Serialize and Deserialize Binary Tree
Hard
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.
Example:
You may serialize the following tree:
1
/ \
2 3
/ \
4 5
as “[1,2,3,null,null,4,5]”
Clarification: The above format is the same as how LeetCode 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.
题意
编写一个类,支持二叉树的序列化和反序列化。注意序列化是无状态的,因此类不能含有非常量的成员变量和静态成员变量。
思路
大家都知道通过先序遍历和中序遍历或中序遍历和后序遍历可以重建二叉树,实际上,如果先序遍历数组中存储null叶子节点,则单独先序遍历就可以重建二叉树。事实上,之所以普通的先序遍历需要中序遍历辅助,是因为没有null叶节点的情况下,在先序遍历数组中无法定位左子树和右子树的长度,需要在中序遍历数组中定位根节点之后得到左子树和右子树。当保存了null叶子节点后,遇到null叶子节点就意味着子树截止。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
private void preorder(TreeNode root, StringBuilder sb) {
if (root == null) {
sb.append("#,");
return;
}
sb.append(root.val);
sb.append(',');
preorder(root.left, sb);
preorder(root.right, sb);
}
private TreeNode reconstruct(LinkedList<String> sq) {
String head = sq.removeFirst();
if (head.equals("#")) {
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(head));
root.left = reconstruct(sq);
root.right = reconstruct(sq);
return root;
}
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) {
return "";
}
StringBuilder sb = new StringBuilder();
preorder(root, sb);
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.isEmpty()) {
return null;
}
String[] sarr = data.split(",");
LinkedList<String> sq = new LinkedList(Arrays.asList(sarr));
TreeNode root = reconstruct(sq);
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));