递归遍历
#include<iostream>
using namespace std;
typedef struct BinTree
{
ElemType data;
struct BinTree* Left;
struct BinTree* Right;
}BinTree;
void PostOrderTraversal(BinTree* BT)//完全二叉树递归遍历
{
if(Bt)
{
//cout<<BT->data<<" ";前序
PostOrderTraversal(BT->Left);
//cout<<BT->data<<" ";中序
PostOrderTraversal(BT->Right);
//cout<<BT->data<<" ";后序
}
}
非递归遍历
//省去了堆栈和二叉树的创建函数
void PostOrderTraversal(BinTree* BT)//二叉树中序堆栈遍历
{
BinTree* T=BT;
stack* S=CreatStack();//创建堆栈并初始化
while(T||!IsEmpty(S))
{
while(T)//将沿途结点压入堆栈,一直向左
{
//cout<<T->data<<" ";先序遍历
push(S,T);
T=T->Left;
}
if(!Isempty(S))
{
T=Pop(S);//弹出结点堆栈
//cout<<T->data<<" ";中序遍历
T=T->Right;//转向右子树
}
}
}
void PostorderTraversal(BinTree* T)//二叉树的后序堆栈遍历
{
BinTree *T, *r=NULL;
Stack S = CreateStack();
T = BT; r = NULL;
while (T || !IsEmpty(S)) {
if (T) {
Push(S, T);
T = T->Left;
}
else {
T = Pop(S);
if (T->Right && T->Right != r) {//右子树存在,则子树访问完全
T = T->Right;
}
else {
Pop(S);
cout<<T->data<<" ";
r = T;//记录访问过的结点
T = NULL;//结点访问完之后重置
}
}
}
}