二叉树的序列化和反序列化(用先序和层)

元素之间用 "_" 分开,遇到用 "#" 隔开

即该序列化为: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));
	 }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值