题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
/*
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) {
StringBuilder sb=new StringBuilder();
//结点为空,以“#”代替
if(root==null){
sb.append("#,");
return sb.toString();
}
//不为空,即以结点值赋值其后
sb.append(root.val+",");
sb.append(Serialize(root.left));
sb.append(Serialize(root.right));
return sb.toString();
}
//反序列化,根据序列化后的字符串数组重建二叉树
int index=-1;
TreeNode Deserialize(String str) {
index++;
if(index>str.length())
return null;
String[] strArr=str.split(",");
TreeNode node=null;
if(!strArr[index].equals("#")){
node=new TreeNode(Integer.valueOf(strArr[index]));
node.left=Deserialize(str);
node.right=Deserialize(str);
}
return node;
}
}