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

JAVA 26天

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

JAVA 26天

等价转换思想:如果将前序的左右子树互换, 就可得到中右左; 再进行逆序, 可以得到 左右中. 因此, 要把前序的代码改为后序, 需要首先将 leftChild 和 rightChild 互换, 然后用一个栈来存储需要输出的字符, 最终反向输出即可.

先序

与中序只有输出的位置不同

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

后序

以中右左的顺序存储到栈中,最后再从栈中取出即后序遍历。

一个栈在遍历二叉树的时候在随时存取,所以需要另一个栈来存储中右左顺序遍历的结点

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


 

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

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

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