二叉树的序列化可以按照先序遍历的方式就行序列化,也可以按照层的方式就行序列化。
package lianxi04;
import java.util.LinkedList;
import java.util.Queue;
public class code04SerializeAndReconstructTree {
public static void main(String[] args) {
Node head=new Node(1);
head.left=new Node(2);
head.right=new Node(3);
head.left.left=new Node(4);
head.left.right=new Node(5);
head.right.left=new Node(6);
head.right.right=new Node(7);
String res=SerializeByPre(head);
System.out.println(res);
Node head2=ReconstructTree(res);
preOrderRecur(head2);
System.out.println();
String res2=SerializeByLevel(head2);
System.out.println(res2);
Node head3=ReconstructTreeByLevel(res2);
preOrderRecur(head3);
}
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data){
this.value=data;
}
}
public static String SerializeByPre(Node head){
if(head==null) return "!#";
String res;
res=head.value+"#";
res+=SerializeByPre(head.left);
res+=SerializeByPre(head.right);
return res;
}
public static Node ReconstructTree(String res){
if(res==null)return null;
String[] ch=res.split("#");
Queue<String> queue=new LinkedList<>();
for(String s:ch){
queue.add(s);
}
return reconPreOrede(queue);
}
public static Node reconPreOrede(Queue<String> queue){
String value=queue.poll();
if(value.equals("!"))
return null;
Node head=new Node(Integer.valueOf(value));
head.left=reconPreOrede(queue);
head.right=reconPreOrede(queue);
return head;
}
public static void preOrderRecur(Node head){
if(head==null) return ;
System.out.print(head.value+" ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
//通过层来进行序列化
public static String SerializeByLevel(Node head){
if(head==null) return "!#";
String res=head.value+"#";
Queue<Node> queue=new LinkedList<>();
queue.add(head);
while(!queue.isEmpty()){
Node node=queue.poll();
if(node.left!=null){
queue.add(node.left);
res+=node.left.value+"#";
}else{res+="!#";}
if(node.right!=null){
queue.add(node.right);
res+=node.right.value+"#";
}else{
res+="!#";
}
}
return res;
}
public static Node ReconstructTreeByLevel(String res){
if(res==null)return null;
String[] s=res.split("#");
int index=0;
Node head=generateNodeByString(s[index++]);
Queue<Node> queue=new LinkedList<>();
queue.add(head);
while(!queue.isEmpty()){
Node node=queue.poll();
node.left=generateNodeByString(s[index++]);
node.right=generateNodeByString(s[index++]);
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
return head;
}
public static Node generateNodeByString(String s){
if(s.equals("!"))return null;
return new Node(Integer.valueOf(s));
}
}