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