#include <stdio.h>
#include <stdlib.h>
#define M 255
typedef struct node{
char data;
struct node *lchild,*rchild;
}TreeNode,*BiTree;
BiTree T;
typedef struct Node{
BiTree data[M];
int top;
}SqStack;
SqStack S;
void InitStack(SqStack &S){
S.top=-1;
}
bool Push(SqStack &S,BiTree e){
if(S.top==M-1){
return false;
}
S.data[++S.top]=e;
return true;
}
bool Pop(SqStack &S,BiTree &x){
if(S.top==-1){
return false;
}
x=S.data[S.top--];
return true;
}
bool StackEmpty(SqStack &S){
if(S.top==-1){
return true;
}
else{
return false;
}
}
void visit(BiTree t){
printf("%c ",t->data);
}
void CreatTree(BiTree &T){
char c;
scanf("%c",&c);
if(c!='#'){
T=(TreeNode *)malloc(sizeof(TreeNode));
T->data=c;
T->lchild=T->rchild=NULL;
CreatTree(T->lchild);
CreatTree(T->rchild);
}
}
void In_PreOrder(BiTree t){
while(!StackEmpty(S) || t){
while(t){
Push(S,t);
visit(t);
t=t->lchild;
}
if(!StackEmpty(S)){
Pop(S,t);
t=t->rchild;
}
}
}
void In_InOrder(BiTree t){
while(!StackEmpty(S) || t){
while(t){
Push(S,t);
t=t->lchild;
}
if(!StackEmpty(S)){
Pop(S,t);
visit(t);
t=t->rchild;
}
}
}
void In_PostOrder(BiTree t){
SqStack si;
InitStack(si);
while(!StackEmpty(si) || t){
while(t){
Push(S,t);
Push(si,t);
t=t->rchild;
}
if(!StackEmpty(si)){
Pop(si,t);
t=t->lchild;
}
}
while(!StackEmpty(S)){
Pop(S,t);
visit(t);
}
}
int main(){
InitStack(S);
CreatTree(T);
printf("\n非递归先序遍历:");
In_PreOrder(T);
printf("\n非递归中序遍历:");
In_InOrder(T);
printf("\n非递归后序遍历:");
In_PostOrder(T);
return 0;
}