import java.util.*;
public class Solution {
//反序列化位置
int index =0;
String Serialize(TreeNode root) {
if(root ==null){
return "#";
}
StringBuilder res = new StringBuilder();
se(root,res);
return res.toString();
}
//处理序列化
private void se(TreeNode root ,StringBuilder str){
if(root==null){
str.append("#");
return;
}
str.append(root.val).append('!');
se(root.left,str);
se(root.right,str);
}
TreeNode Deserialize(String str) {
//空序列对应空树
if(str == "#")
return null;
TreeNode res = de(str);
return res;
}
private TreeNode de(String str){
//到达叶节点,构建完毕,返回继续构建父节点
if(str.charAt(index) =='#'){
index++;
//全为空节点,直接返回null
return null;
}
//得到节点值
int val =0;
//遇到分隔符或者结尾时结束
while(str.charAt(index) !='!' && index !=str.length()){
val = val *10 +((str.charAt(index)) -'0');
index ++;
}
//新建节点
TreeNode root = new TreeNode(val);
//判断当前序列化位置
if(index==str.length()){
return root;
}else{
index++;
}
//递归
root.left = de(str);
root.right = de(str);
return root;
}
}