题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
分析
结点为空时用“#”代替,反序列化时,遇到“#”输出null
代码
public class SerializeTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root = new TreeNode(1);
root.left = null;
root.right = new TreeNode(2);
root.right.left = new TreeNode(3);
root.right.right = null;
String str = serialize(root);
System.out.println(str);
TreeNode node = deSerialize(str);
System.out.println(node);
}
public static String serialize(TreeNode root){
StringBuilder sb = new StringBuilder();
if(root == null){
sb.append("#,");
return sb.toString();
}
sb.append(root.value+",");
sb.append(serialize(root.left));
sb.append(serialize(root.right));
return sb.toString();
}
public static int index = 0;
public static TreeNode deSerialize(String str){
String[] strs = str.split(",");
if(strs[index].equals("#")){
index++;
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(strs[index]));
index++;
root.left = deSerialize(str);
root.right = deSerialize(str);
return root;
}
}
---------------------
作者:另一个我竟然存在
来源:CSDN
原文:https://blog.csdn.net/qq_24034545/article/details/83660603
版权声明:本文为博主原创文章,转载请附上博文链接!
|
|