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

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

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 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5697786.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存