/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
String Serialize(TreeNode root) {
if(root == null) {
return "#_" ;
}
return root.val + "_" + Serialize(root.left) + Serialize(root.right) ;
}
int index = 0 ;
TreeNode Deserialize(String str) {
if(index >= str.length()) {//索引超过直接返回null
return null ;
}
if(str.charAt(index) == '#') {
index+=2 ;//讲索引位置移动到下一个有效字符
return null ;
}
int i = index ;//寻找完整的数
while(str.charAt(i) >= '0' && str.charAt(i) <= '9') {
i++ ;
}
TreeNode root = new TreeNode(Integer.parseInt(str.substring(index,i))) ;//构造完整数的节点
index = i+1 ;//讲索引位置移动到下一个有效字符
root.left = Deserialize(str) ;//递归
root.right = Deserialize(str) ;
return root ;
}
}