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.
Clarification: The input/output 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.
Constraints:
- The number of nodes in the tree is in the range [0, 10^4].
- -1000 <= Node.val <= 1000
Example
Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]
思路
序列化的题,最主要的就是转成字符串后要用什么做标记,再转回去,这边val只能位数字,那就直接用空格来做标记了,如果是String的话,就要记录每个String的长度再加一个标志位
题解
String result = "";
Integer index = 0;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
dfsSerialize(root);
return result;
}
public void dfsSerialize(TreeNode root) {
if (root == null) {
// 为null就加上结束标记#再加一个空格
result += "# ";
return;
}
// 中左右 先序遍历 依次记录
result += root.val + " ";
dfsSerialize(root.left);
dfsSerialize(root.right);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
// 利用标记位空格切分成数组,这样就可以直接取值,如果通过String取的话还要考虑数字长度是否为负数等等
return dfsDeserialize(data.split(" "));
}
public TreeNode dfsDeserialize(String[] val) {
if (val[index].equals("#")) {
// #为结束符,下标+1
index++;
return null;
}
TreeNode cur = new TreeNode();
// 继续中左右 依次取出
cur.val = Integer.parseInt(String.valueOf(val[index++]));
cur.left = dfsDeserialize(val);
cur.right = dfsDeserialize(val);
return cur;
}
标签:Binary,TreeNode,Deserialize,val,Hard,tree,null,root,String
From: https://www.cnblogs.com/tanhaoo/p/17103709.html