今天完成二叉树前后序的非递归栈遍历,先贴代码
/**
* Pre-order visit with stack.
*/
public void preOrderVisitWithStack(){
ObjectStack tempStack=new ObjectStack();
BinaryCharTree tempNode=this;
while (tempNode!=null||!tempStack.isEmpty()){
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 tempNodeA=this;
BinaryCharTree tempNodeB=null;
while(tempNodeA!=null||!tempStack.isEmpty()){
if(tempNodeA!=null){
tempStack.push(tempNodeA);
tempNodeA=tempNodeA.leftChild;
}else {
tempNodeA=(BinaryCharTree) tempStack.getTop();
if(tempNodeA.rightChild!=null&&tempNodeB!=tempNodeA.rightChild){
tempNodeA=tempNodeA.rightChild;
}else
{
tempNodeA=(BinaryCharTree) tempStack.pop();
System.out.print("" + tempNodeA.value + " ");
tempNodeB=tempNodeA;
tempNodeA=null;
}//Of if
}//Of if
}// Of while
}//of postOrderVisitWithStack
前序遍历的话根中序类似,只是输出位置稍作修改,后序就麻烦一些。需要记录访问结点的右子树是否为空或者刚被访问过,这样才可以访问根节点。老师提到的转换思路那个以前没见过,代码贴一下:
/**
*********************
* 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
二叉树的遍历, 总共有 6 种排列: 1) 左中右 (中序); 2) 左右中 (后序); 3) 中左右 (前序); 4) 中右左; 5) 右左中; 6) 右中左. 我们平常关心的是前三种, 是因为我们习惯于先左后右. 如果要先右后左, 就相当于左右子树互换, 这个是很容易做到的.
如果将前序的左右子树互换, 就可得到 4) 中右左; 再进行逆序, 可以得到 2) 左右中. 因此, 要把前序的代码改为后序, 需要首先将 leftChild 和 rightChild 互换, 然后用一个栈来存储需要输出的字符, 最终反向输出即可. 这种将一个问题转换成另一个等价问题的方式,
————————————————
版权声明:本文为CSDN博主「闵帆」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/minfanphd/article/details/116975721
老师博客里这么写的,老师提到的这个可能更易于理解一些,但是增加了复杂度,但可能影响不大?(都是O(n)),上面我写的是去年考研时学到的思路,求公共祖先、路径方面我觉得会方便一些