二叉树的序列化和反序列化

题目其实就是将二叉树转化成字符串同时保留树的空间信息.可以用空占位符占住空节点的位置,用来描述树的实际结构.

先序遍历的方式序列化代码如下:

	public static String serialByPre(Node head){
		if(head == null){
			return "#_";
		}
		String res = head.data + "_";
		res += serialByPre(head.left);
		res += serialByPre(head.right);
		return res;
	}

 反序列化还是按照中 > 左 > 右的先序遍历顺序拼接

	public static Node deserialPre(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 deserialPre(queue);
	}
	
	public static Node deserialPre(Queue<String> queue){
		String value = queue.poll();
		if(value.equals("#")){
			return null;
		}
		
		Node head = new Node(Integer.valueOf(value));
		head.left = deserialPre(queue);
		head.right = deserialPre(queue);
		return head;
	}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值