利用栈实现中序遍历。
建立的栈和前几天的类似,都是通用性的,依靠强制类型转换, 支持不同的数据类型。
下面写一下这个通用性的栈
public class ObjectStack {
/*栈深度*/
public static final int MAX_DEPTH = 10;
/*实际栈深*/
int depth;
/*存储数值*/
Object[] data;
/**
建立一个空的顺虚表
*/
public ObjectStack() {
depth = 0;
data = new Object[MAX_DEPTH];
}// Of the first constructor
/**
重写toString()方法
*/
public String toString() {
String resultString = "";
for (int i = 0; i < depth; i++) {
resultString += data[i];
} // Of for i
return resultString;
}
出栈入栈操作:
//入栈
public boolean push(Object paraObject) {
if (depth == MAX_DEPTH) {
System.out.println("Stack full.");
return false;
}
data[depth] = paraObject;
depth++;
return true;
}
//出栈
public Object pop() {
if (depth == 0) {
System.out.println("Nothing to pop.");
return '\0';
}
Object resultObject = data[depth - 1];
depth--;
return resultObject;
}
还增加了判空方法:
//判空
public boolean isEmpty() {
if (depth == 0) {
return true;
}//Of if
return false;
}
再main方法中对上述方法进行调用:
public static void main(String args[]) {
ObjectStack tempStack = new ObjectStack();
for (char ch = 'a'; ch < 'm'; ch++) {
tempStack.push(new Character(ch));
System.out.println("The current stack is: " + tempStack);
} // Of for i
char tempChar;
for (int i = 0; i < 12; i++) {
tempChar = ((Character)tempStack.pop()).charValue();
System.out.println("Poped: " + tempChar);
System.out.println("The current stack is: " + tempStack);
} // Of for i
}
验证实例:
下面是利用我们上面写的通用性栈,来实现中序遍历。
其思想为:当树不为空时,入栈,接下来访问其左孩子。当左孩子不存在时,栈内元素出栈输出并访问其右孩子,直至访问完树内元素,讲栈内元素全部输出。可以手动模拟一遍,很容易理解。
public void inOrderVisitWithStack() {
ObjectStack tempStack = new ObjectStack();//创建栈
BinaryCharTree tempNode = this;//二叉树
/* 二叉树遍历 */
while (!tempStack.isEmpty() || tempNode != null) {
if (tempNode != null) {
tempStack.push(tempNode);
tempNode = tempNode.leftChild;
} else {
tempNode = (BinaryCharTree) tempStack.pop();
System.out.print("" + tempNode.value + " ");
tempNode = tempNode.rightChild;
}
}
}
个人还是倾向于递归(毕竟代码简单,好想),但是今天主要是用来通用性栈