剑指offer-37 序列化二叉树
题目:
思路:
自己解答:
这个有错误
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);
}
}
犯的错误:
反序列化时不能正确的链接各个节点
注意:
- 引用类型赋值为null时,无论里面怎么修改,出来还是null
- 对于这种从上往下需要链接,可以像下面代码一样利用return返回来链接
- String,StringBuffer,StringBuilder三者区别https://www.cnblogs.com/weibanggang/p/9455926.html
别人解答:
/*
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;
}
}
原文地址:https://www.cnblogs.com/muche-moqi/p/12393042.html
时间: 2024-10-11 20:37:39