#include<iostream>
using namespace std;
#define Stack_Init_Size 100
#define StackIncrement 10
#define NULL 0
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct
{
BiTree *base,*top;
int stacksize;
}SqStack;
void CreateBiTree(BiTree &T)
{
char ch;
ch=getchar();
if(ch=='#') T=NULL;
else
{
T=(BiTNode *)malloc(sizeof(BiTNode));
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
void Addspace(SqStack &S)
{
S.base=(BiTNode **)realloc(S.base,(S.stacksize+StackIncrement)*sizeof(BiTNode));
if(!S.base)cout<<"分配失败"<<endl;
S.top=S.base+S.stacksize;
S.stacksize+=StackIncrement;
}
int StackEmpty(SqStack S)
{
if(S.base==S.top)return 1;
else return 0;
}
void Push(SqStack &S,BiTree T)
{
if(S.top-S.base>=S.stacksize)
Addspace(S);
*(S.top++)=T;
}
void Pop(SqStack &S,BiTree *T)
{
*T=*(--S.top);
}
void InitStack(SqStack &S)
{
S.base=(BiTNode **)malloc((Stack_Init_Size)*sizeof(BiTNode));
S.top=S.base;
S.stacksize=Stack_Init_Size;
}
void Visit(BiTree T)
{
cout<<T->data;
}
void PreOrder(BiTree T)
{
SqStack S;
InitStack(S);
BiTree p;
p=T;
while(p||!StackEmpty(S))
{
while(p) //若p非空则压栈根结点的右指针,p指向它的左孩子
{
Visit(p);
Push(S,p->rchild);
p=p->lchild;
}
Pop(S,&p);
}
}
void InOrder(BiTree T)
{
SqStack S;
InitStack(S);
BiTree p;
p=T;
while(p||!StackEmpty(S))
{
while(p) //遍历左子树,p非空则将结点压入栈,P指向左孩子
{
Push(S,p);
p=p->lchild;
}
Pop(S,&p);
Visit(p);
p=p->rchild;
}
}
void PostOrder(BiTree T)
{
BiTree Tree[Stack_Init_Size];
int tag[Stack_Init_Size],top=0; //tag为是否出栈的标志
do {
while(T)
{
top++;
Tree[top]=T;
tag[top]=0; //tag为0不出栈
T=T->lchild; //遍历左子树
}
if(top>0)
{
if(tag[top]==1) //tag为1出栈
{
cout<<Tree[top]->data;
top--;
}
else
{
T=Tree[top];
T=T->rchild;
tag[top]=1;
}
}
}while(top>0);
}
int main()
{
cout<<"扩展二叉树先序输入: "<<endl;
BiTree T;
CreateBiTree(T);
cout<<"先序遍历结果: "<<endl;
PreOrder(T);
cout<<endl;
cout<<"中序遍历结果: "<<endl;
InOrder(T);
cout<<endl;
cout<<"后序遍历结果: "<<endl;
PostOrder(T);
cout<<endl;
return 0;
}