- 二叉樹的序列化與反序列化
public class Codec {
public String serialize1(TreeNode root) {
if(root == null){
return "#!";
}
String str = root.val + "!";
str += serialize(root.left);
str += serialize(root.right);
return str;
}
public String serialize(TreeNode root) {
StringBuilder res = ser_help(root,new StringBuilder());
return res.toString();
}
public StringBuilder ser_help(TreeNode root,StringBuilder str){
if(root == null){
str.append("#!");
return str;
}
str.append(root.val);
str.append("!");
str = ser_help(root.left,str);
str = ser_help(root.right,str);
return str;
}
public TreeNode deserialize(String data) {
String []arr=data.split("!");
Queue <String> queue=new LinkedList<String>();
for(int i=0;i<arr.length;i++){
queue.offer(arr[i]);
}
return deserialize(queue);
}
public TreeNode deserialize(Queue <String> queue){
String str=queue.poll();
if(str.equals("#")){
return null;
}
TreeNode root=new TreeNode(Integer.parseInt(str));
root.left=deserialize(queue);
root.right=deserialize(queue);
return root;
}
}