日撸代码300行学习笔记 Day 26

 1.二叉树深度遍历的栈实现 (前序和后序)

与昨天类似,只增加了相应的部分代码。

//栈,先序
	public void preOrderVisitWithStack() {
		ObjectStack tempStack = new ObjectStack();
		BinaryCharTree2 tempNode = this;
		while (!tempStack.isEmpty() || tempNode != null) {
			if (tempNode != null) {
				System.out.print("" + tempNode.value + " ");
				tempStack.push(tempNode);
				tempNode = tempNode.leftChild;
			} else {
				tempNode = (BinaryCharTree2) tempStack.pop();
				tempNode = tempNode.rightChild;
			} // Of if
		} // Of while
	}// Of preOrderVisitWithStack
	
	//栈,后序
	public void postOrderVisitWithStack() {
		ObjectStack tempStack = new ObjectStack();
		BinaryCharTree2 tempNode = this;
		ObjectStack tempOutputStack = new ObjectStack();

		while (!tempStack.isEmpty() || tempNode != null) {
			if (tempNode != null) {
				// Store for output.
				tempOutputStack.push(new Character(tempNode.value));
				tempStack.push(tempNode);
				tempNode = tempNode.rightChild;
			} else {
				tempNode = (BinaryCharTree2) tempStack.pop();
				tempNode = tempNode.leftChild;
			} // Of if
		} // Of while

		// Now reverse output.
		while (!tempOutputStack.isEmpty()) {
			System.out.print("" + tempOutputStack.pop() + " ");
		} // Of while
	}// Of postOrderVisitWithStack

	// main
	public static void main(String args[]) {
		// 逆向通过编号创建二叉树,并返回链接关系,最后进行前中后序遍历
		char[] tempCharArray = { 'A', 'B', 'C', 'D', 'E', 'F' };
		int[] tempIndicesArray = { 0, 1, 2, 4, 5, 12 };
		BinaryCharTree2 tempTree2 = new BinaryCharTree2(tempCharArray, tempIndicesArray);

		System.out.println("\r\nIn-order visit with stack:");
		tempTree2.inOrderVisitWithStack();
		System.out.println("\r\nPre-order visit with stack:");
		tempTree2.preOrderVisitWithStack();
		System.out.println("\r\nPost-order visit with stack:");
		tempTree2.postOrderVisitWithStack();
	}// Of main

运行结果:

2.总结 

上述内容仅仅是完成了相应的代码,就目前自己理解看懂过后,自己尝试着写这两种遍历还是有难度,代码这玩意,不能只是看看就行,一定要亲自动手尝试才行,就以这个树的遍历来说,这么有规律性的东西,有时候以为自己懂了,但是在实际写的过程当中,感觉到会漏洞百出。其次是在这个中序以及后序遍历中,看到了老师贴出来的莫峦奇的版本,将其调换顺序后,再逆转栈,这种思想确实惊奇,将一个问题转换成另外一个问题,前中后序遍历学了这么多遍了,但是自己在之前的学习里面从来都没有想到过这种方法,一昧去沿着平常的方法做,属实应该多去思考思考。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值