非递归后序遍历二叉树:
#include <iostream>
using namespace std;
/*
*writer:yaojinhui
*/
#define MAXSIZE 100
typedef struct BiTNode {
char data;
int isSecond; // 增加标志位,初始值赋为0
struct BiTNode *lchild,*rchild;
} BiTNode,*BiTree;
typedef struct
{
BiTree *base,*top;
int stacksize;
}SqStack;
BiTree e;
int InitStack(SqStack &S)
{
S.top=S.base=new BiTree[MAXSIZE];
S.stacksize=MAXSIZE;
return 1;
}
int Push(SqStack &S,BiTree e)
{
if(S.top-S.base==S.stacksize)
return 0;
*S.top++=e;
return 1;
}
int Pop(SqStack &S,BiTree &e)
{
if(S.top==S.base)
return 0;
e=*--S.top;
return 1;
}
int StackEmpty(SqStack S)
{
if(S.top==S.base)
return 1;
else
return 0;
}
void createBiTree(BiTree &T)
{
char ch;
cin>>ch;
if(ch=='#')
T=NULL;
else
{
T=new BiTNode;
T->data=ch;
createBiTree(T->lchild);
createBiTree(T->rchild);
}
}
// 后序遍历1
// 后序遍历2
void printTreeLast(BiTree T)
{
BiTree tmp = T;
SqStack S;
InitStack(S);
SqStack S2;
InitStack(S2);
while(tmp) {
Push(S2, tmp); // 打印改为压栈,临时保存起来
Push(S, tmp);
tmp = tmp->rchild;
}
while(!StackEmpty(S)) {
Pop(S,e);
tmp = e;
tmp = tmp->lchild;
while (tmp) {
Push(S2, tmp);
Push(S, tmp);
tmp = tmp->rchild;
}
}
// 再依次打印栈中的节点
while(!StackEmpty(S2)) {
Pop(S2,e);
BiTree tmp = e;
cout<<tmp->data<<" ";
// printf("%d\n", tmp->data);
}
}
int main()
{
SqStack S;
BiTree T;
createBiTree(T);
printTreeLast(T);
return 0;
}