题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
思路:
可以用树的先序遍历树,依次保存。但是要注意的时, 空节点使用“ #! ”来保存,正常节点用“A!” 来保存。
Java代码:
public class Serialize_tree {
public static String serialize(TreeNode root) {
// write your code here
StringBuilder sb = new StringBuilder();
preview1(sb, root);
return sb.toString();
}
public static void preview1 (StringBuilder sb, TreeNode root){
if(root==null){
sb.append("#!");
return;
}else{
sb.append(root.val+"!");
}
preview1(sb, root.left);
preview1(sb, root.right);
}
public static int index = -1;
public static TreeNode deserialize(String data) {
// write your code here
if(data.length()==0){
return null;
}
String[] s = data.split("!");
return preview2(s);
}
public static TreeNode preview2(String[] s){
index++;
while(s[index]!="#"){
TreeNode node = new TreeNode(Integer.valueOf(s[index]));
node.left = preview2(s);
node.right = preview2(s);
return node;
}
return null;
}
public static void main(String[] args) {
TreeNode node = new TreeNode(10);
TreeNode node11 = new TreeNode(8);
TreeNode node22 = new TreeNode(12);
node.left = node11;
node.right = node22;
String ss = serialize(node);
System.out.println(ss);
// TreeNode node3 = Deserialize(ss);
// System.out.println(node3.val);
}
}