请实现两个函数,分别用来序列化和反序列化二叉树
public class Solution {
int index=-1;
public String Serialize(TreeNode root) {
StringBuilder strb = new StringBuilder();
if(root==null){
strb.append("#,");
return strb.toString();
}
strb.append(root.val);
strb.append(",");
strb.append(Serialize(root.left));
strb.append(Serialize(root.right));
return strb.toString();
}
public TreeNode Deserialize(String str) {
index++;
String stra[] = str.split(",");
TreeNode node = null;
if(!stra[index].equals("#")){
node = new TreeNode(Integer.valueOf(stra[index]));
node.left = Deserialize(str);
node.right=Deserialize(str);
}
return node;
}
}
网友评论