标签:containe letter substr tab tps port ati ber style
题目:
思路:
自己解答:
这个有错误
public class Solution {
String Serialize(TreeNode root) {
if(root == null) return "#!";
StringBuilder bd = new StringBuilder();
serializeCore(root, bd);
return bd.toString();
}
private void serializeCore(TreeNode root, StringBuilder bd){
if(root == null){
bd.append("#!");
return;
}
bd.append(root.val);
bd.append("!");
serializeCore(root.left, bd);
serializeCore(root.right, bd);
}
TreeNode Deserialize(String str) {
if(str == null || str.length() <= 1) return null;
TreeNode res = null;
deserializeCore(res, str, 0);
return res;
}
private int end;
private void deserializeCore(TreeNode res, String str, int start){
end = str.indexOf("!", start);
if(end == -1) return;
String num = str.substring(start, end);
if(num.equals("#")) return;
res = new TreeNode(Integer.parseInt(num));
res.left = null;
res.right = null;
deserializeCore(res.left, str, ++end);
deserializeCore(res.right, str, ++end);
}
}
犯的错误:
反序列化时不能正确的链接各个节点
注意:
别人解答:
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int index = -1;
String Serialize(TreeNode root) {
StringBuffer sb = new StringBuffer();
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();
}
TreeNode Deserialize(String str) {
index++;
int len = str.length();
if(index >= len){
return null;
}
String[] strr = str.split(",");
TreeNode node = null;
if(!strr[index].equals("#")){
node = new TreeNode(Integer.valueOf(strr[index]));
node.left = Deserialize(str);
node.right = Deserialize(str);
}
return node;
}
}
标签:containe letter substr tab tps port ati ber style
原文地址:https://www.cnblogs.com/muche-moqi/p/12393042.html