栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java第27天——二叉树的深度遍历的栈实现(前序和后序)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java第27天——二叉树的深度遍历的栈实现(前序和后序)

1,前序和后序的区别,仅仅在于输出语句的位置不同。

2,二叉树的遍历, 总共有 6 种排列: 1) 左中右 (中序); 2) 左右中 (后序); 3) 中左右 (前序); 4) 中右左; 5) 右左中; 6) 右中左; 我们平常关心的是前三种, 是因为我们习惯于先左后右. 如果要先右后左, 就相当于左右子树互换, 这个是很容易做到的.

3,如果将前序的左右子树互换, 就可得到 4) 中右左; 再进行逆序, 可以得到 2) 左右中. 因此, 要把前序的代码改为后序, 需要首先将 leftChild 和 rightChild 互换, 然后用一个栈来存储需要输出的字符, 最终反向输出即可. 这种将一个问题转换成另一个等价问题的方式, 无论在数学还是计算机领域, 都极度重要.。

4,如果不按上述方式, 直接写后序遍历, 就会复杂得多, 有双重的 while 循环。

	public void preOrderVisitWithStack() {
		ObjectStack tempStack = new ObjectStack();
		BinaryCharTree tempNode = this;
		while (!tempStack.isEmpty() || tempNode != null) {
			if (tempNode != null) {
				System.out.print("" + tempNode.value + " ");
				tempStack.push(tempNode);
				tempNode = tempNode.leftChild;
			} else {
				tempNode = (BinaryCharTree) tempStack.pop();
				tempNode = tempNode.rightChild;
			} // of if
		} // of while
	}// of preOrderVisitWithSatck

	
	public void postOrderVisitWithStack() {
		ObjectStack tempStack = new ObjectStack();
		BinaryCharTree 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 = (BinaryCharTree) tempStack.]pop();
				tempNode = tempNode.leftChild;
			} // Of if
		} // Of while

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

public static void main(String args[]) {


		System.out.println("rn前序遍历:");
		temptree2.preOrderVisit();
		System.out.println("rn中序遍历:");
		temptree2.inOrderVisit();
		System.out.println("rn后序遍历:");
		temptree2.postOrderVisit();

		System.out.println("rnIn-order visit with stack:");
		temptree2.inOrderVisitWithStack();
		System.out.println("rnpre-order visit with stack:");
		temptree2.preOrderVisitWithStack();
		System.out.println("rnpost-order visit with stack:");
		temptree2.postOrderVisitWithStack();
	}// of main

}

why

 

这里原来是我的前面写ObjectStack的是把depth用static设成了静态常量,导致了这里的tempStack和tempOutputStack还是用的同一个栈。原来如此,当时写栈的时候没有想这么多,看来写代码不能只想着自己舒服,还是要想想老师为什么要这样写。static还是不要乱用。

运行结果(部分)

前序遍历:
A B D C E F 
中序遍历:
B D A E F C 
后序遍历:
D B F E C A 
In-order visit with stack:
B D A E F C 
pre-order visit with stack:
A B D C E F 
post-order visit with stack:
D B F E C A 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/697655.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号