算法优解(11)-二叉树的序列化和反序列化

来自左神书中的一道题,在左神核心代码的基础上,添加了二叉树的构建和前序遍历操作,将这道题完善成了一个小Demo,和各位共勉。

题目:

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

名词解释:

* 二叉树的序列化:二叉树被记录成文件
* 二叉树的反序列化:通过文件重建二叉树

思路:

我们通过先序遍历实现序列化,假设序列化的结果字符串为str,初识为"",先序遍历二叉树,如果遇到null节点就在str末尾加上"#!","#"表示这个节点为空, "!"表示一个值的结束,如果节点值为x,就在str末尾加上"3!"。

我们测试的二叉树如下:

* 二叉树: 
*                 1 
*              2     3 
*            4  5  6   7 
*           8 9

先序遍历序列化结果:1!2!4!8!#!#!9!#!#!5!#!#!3!6!#!#!7!#!#!

逆序列化反之即可。


核心算法

序列化:

	public static String serialByPre(Node head){
		if(head == null){
			return "#!";
		}
		String s = head.data + "!";
		s += serialByPre(head.leftChild);
		s += serialByPre(head.rightChild);
		return s;
	}

反序列化:

	public static Node reconByPreString(String preStr){
		String values[] = preStr.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 value = queue.poll();
		if(value.equals("#")){
			return null;
		}
		Node head = new Node(Integer.valueOf(value));
		head.leftChild = reconPreOrder(queue);
		head.rightChild = reconPreOrder(queue);
		return head;
	}

先序遍历:

	public static void preOrderTraverse(Node node) {
		if (node == null)
			return;
		System.out.print(node.data + " ");
		preOrderTraverse(node.leftChild);
		preOrderTraverse(node.rightChild);
	}

测试代码:

二叉树的构建:

	public void createBinTree() {
		// 将一个数组的值依次转换为Node节点
		for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) {
			nodeList.add(new Node(array[nodeIndex]));
		}
		// 对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树
		for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) {
			// 左孩子
			nodeList.get(parentIndex).leftChild = nodeList
					.get(parentIndex * 2 + 1);
			// 右孩子
			nodeList.get(parentIndex).rightChild = nodeList
					.get(parentIndex * 2 + 2);
		}
		// 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理
		int lastParentIndex = array.length / 2 - 1;
		// 左孩子
		nodeList.get(lastParentIndex).leftChild = nodeList
				.get(lastParentIndex * 2 + 1);
		// 右孩子,如果数组的长度为奇数才建立右孩子
		if (array.length % 2 == 1) {
			nodeList.get(lastParentIndex).rightChild = nodeList
					.get(lastParentIndex * 2 + 2);
		}
	}

main方法:

	private int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
	private static List<Node> nodeList = new LinkedList<Node>();;
	
	public static void main(String[] args) {
		SerialAndReconTest binTree = new SerialAndReconTest();
		binTree.createBinTree();
		/*
		 * 二叉树: 
		 * 		   1 
		 * 		2     3 
		 *            4  5  6   7 
		 *           8 9
		 */
		// nodeList中第0个索引处的值即为根节点
		Node root = nodeList.get(0);
		System.out.println(serialByPre(root));
		//1!2!4!8!#!#!9!#!#!5!#!#!3!6!#!#!7!#!#!
		
//		String preStr = "1!2!4!8!#!#!9!#!#!5!#!#!3!6!#!#!7!#!#!";
//		Node root = reconByPreString(preStr);
//		preOrderTraverse(root);
	}

输出结果:

1!2!4!8!#!#!9!#!#!5!#!#!3!6!#!#!7!#!#!

1 2 4 8 9 5 3 6 7 


原创不易,转载请注明出处哈。

权兴权意

http://blog.csdn.net/hxqneuq2012/article/details/53290522



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值