Serilization(序列化)
1. 二叉树的序列化
1.1 普通二叉树序列化
297. Serialize and Deserialize Binary Tree
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]"
Note:
Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
前序遍历,序列化时将树变成一个字符串,每个节点的值用一个分隔符“,”隔开,null节点用“NN”表示。
反序列化时用递归的方式处理这个字符串。
TC: O(n), SC: O(n)
public class Codec {
private static final String SPLITER = ",";
private static final String NN = "N";
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
// TODO
StringBuilder builder = new StringBuilder();
serialHelper(root, builder);
return builder.toString();
}
private void serialHelper(TreeNode root, StringBuilder builder) {
if (root == null) {
builder.append(NN).append(SPLITER);
return;
}
builder.append(root.val).append(SPLITER);
serialHelper(root.left, builder);
serialHelper(root.right, builder);
}
private int idx;
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
String[] array = data.split(SPLITER);
return deserialHelper(array);
}
private TreeNode deserialHelper(String[] array) {
if (NN.equals(array[idx])) {
idx++;
return null;
}
TreeNode node = new TreeNode(Integer.parseInt(array[idx++]));