遇到的问题:
我们遇到的关于二叉树的很多题都是代逻辑十分重要,只有理解背后的逻辑才能把代码看懂,才能将代码编出来.
解决方法:
对于二叉树的非递归遍历其实我之前就看过很多次代码了,也是因为各种需求的原因,不过我之前是用c语言写出来的就是了,对于二叉树的前序遍历和中序遍历基本上一致,只是在输出语句的位置上稍微有一点不同,具体可以参考我25天写的中序遍历.但是对于后序遍历我们需要建立两个栈,第一次先将右子树入第一个栈,再将左子树入第二个栈,最后再将第一个栈的元素返回出来到第二个栈.
代码展示:
主函数类:
package Day_26;
import Day_21.BinaryCharTree;
import java.util.Arrays;
public class demo1 {
/**
* ********************
* The entrance of the program.
*
* @param args Not used now.
* ********************
*/
public static void main(String args[]) {
char[] tempCharArray = {'A', 'B', 'C', 'D', 'E', 'F'};
int[] tempIndicesArray = {0, 1, 2, 4, 5, 12};
BinaryCharTree tempTree2 = new BinaryCharTree(tempCharArray, tempIndicesArray);
System.out.println("\r\nPre-order visit:");
tempTree2.preOrderVisit();
System.out.println("\r\nIn-order visit:");
tempTree2.inOrderVisit();
System.out.println("\r\nPost-order visit:");
tempTree2.postOrderVisit();
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
}
在BinaryCharTree里面补充的代码:
/26天补充代码
/**
*********************
* Pre-order visit with stack.
*********************
*/
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 preOrderVisitWithStack
/**
*********************
* Post-order visit with stack.
*********************
*/
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
运行结果: