元素之间用 "_" 分开,遇到用 "#" 隔开
即该序列化为:A_B_D_#_#_E_#_#_C_#_F
利用先序遍历的一大特点(访问顺序):中左右. 在使用递归便可得到它的序列化
public static String serialByPre(Node head){
if(head==null){
return "#_";
}
String res=head.value+"_";
res+=serialByPre(head.left);
res+=serialByPre(head.right);
return res;
}
反序列化是指将A_B_D_#_#_E_#_#_C_#_F转换成二叉树的形式
这里需要使用一个队列(FIFO),在使用递归,在遇到 "#"时返回null,而且根据的递归特性,很容易知道左子树和右子树
public static Node reconByPreString(String str){
String[] values=str.split("_");
Queue<String> queue=new LinkedList<String>();
for(int i=0;i<values.length;i++){
queue.offer(values[i]);
}
return reconPreOrder(queue);
}
public static Node reconPreOrder(Queue<String> queue){
String str=queue.poll();
if(str.equals("#")){
return null;
}else{
Node head=new Node(new Integer(str));
head.left=reconPreOrder(queue);
head.right=reconPreOrder(queue);
return head;
}
}
用层的方式进行序列化。也就是:A_B_C_D_E_#_F_#_#_#_#_#_#
public static String levelByPre(Node head){
if(head==null){
return "#";
}
Queue<Node> queue=new LinkedList<Node>();
String res=head.value+"_";
queue.offer(head);
while(!queue.isEmpty()){
head=queue.poll();
if(head.left!=null){
res+=head.left.value+"_";
queue.offer(head.left);
}else{
res+="#_";
}
if(head.right!=null){
res+=head.right.value+"_";
queue.offer(head.right);
}else{
res+="#_";
}
}
return res;
}
反序列化:
public static Node reconlevelByPre(String str){
String[] values=str.split("_");
int index=0;
Node head=getNodeByString(values[index++]);
Queue<Node> queue=new LinkedList<Node>();
if(head!=null){
queue.offer(head);
}
Node node=null;
while(!queue.isEmpty()){
node=queue.poll();
node.left=getNodeByString(values[index++]);
node.right=getNodeByString(values[index++]);
if(node.left!=null){
queue.offer(node.left);
}
if(node.right!=null){
queue.offer(node.right);
}
}
return head;
}
public static Node getNodeByString(String str){
if(str.equals("#")){
return null;
}
return new Node(new Integer(str));
}