题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
AC代码1
曾经见到过一个非常令人吃惊的代码。
因为题目中没有规定序列化的方法,因此没办法检验序列化后结果的正确性,这也正是BUG所在。
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
TreeNode root = null;
String Serialize(TreeNode root) {
this.root = root;
return null;
}
TreeNode Deserialize(String str) {
return this.root;
}
}
AC代码2
/*
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 "";
StringBuilder sb = new StringBuilder();
SerializeCore(root, sb);
return sb.toString();
}
void SerializeCore(TreeNode root, StringBuilder sb) {
if(root == null) {
sb.append("$,");
return;
}
sb.append(root.val);
sb.append(',');
SerializeCore(root.left, sb);
SerializeCore(root.right, sb);
}
int start = 0;
TreeNode Deserialize(String str) {
if(str.equals("")) return null;
return DeserializeCore(str);
}
private TreeNode DeserializeCore(String str){
if(start == str.length()) return null;
int ch = str.charAt(start);
if(ch == '$') {
start++;
start++;
return null;
}
TreeNode root = new TreeNode(0);
int val = 0;
while(ch >= '0' && ch <= '9'){
val = val * 10 + (ch - '0');
start++;
ch = str.charAt(start);
}
start++;
root.val = val;
root.left = DeserializeCore(str);
root.right = DeserializeCore(str);
return root;
}
}