#include<stdio.h>
#include<stdlib.h>
#define MAX 100
typedef struct Node
{
int data;
struct Node *Lchild;
struct Node *Rchild;
}BTNode, *BTtree;
typedef struct
{
BTtree date[MAX];
int top;
}Sstack;
BTtree creat();//创建二叉树
Sstack Init_Sstack();//初始化栈
int Push(Sstack *s, BTtree x);//入栈
BTtree pop(Sstack *s, BTtree e);//出栈
void BeforeOrder(BTtree L);//前序遍历
void midOrder(BTtree L);//中序遍历
void BackOrder(BTtree L);//后序遍历
int main(void)
{
BTtree s;
s = creat();
BeforeOrder(s);
printf("\n");
midOrder(s);
printf("\n");
BackOrder(s);
return 0;
}
Sstack Init_Sstack()
{
Sstack *s;
s = (Sstack*)malloc(sizeof(Sstack));
s->top = -1;
return *s;
}
int Empty(Sstack s)
{
if (s.top == -1)
return 1;
else
return 0;
}
BTtree pop(Sstack *s, BTtree e)
{
if (Empty(*s))
return 0;
else {
e = s->date[s->top];
s->top--;
return e;
}
}
int Push(Sstack *s, BTtree x)
{
if (s->top == MAX - 1)
return 0;
else {
s->top++;
s->date[s->top] = x;
return 1;
}
}
BTtree top(Sstack *s)
{
if (Empty(*s))
return 0;
else {
return s->date[s->top];
}
}
BTtree creat()
{
char ch;
BTtree s;
ch = getchar();
if (ch == '#')
s = NULL;
else
{
s = (BTtree)malloc(sizeof(BTNode));
s->data = ch;
s->Lchild = creat();
s->Rchild = creat();
}
return s;
}
void BeforeOrder(BTtree L){ //前序遍历
Sstack s;
BTtree p;
s =Init_Sstack();
p=L;
while(p!=NULL||!Empty(s)) {
while(p!=NULL){
printf("%c", p->data);
Push(&s,p);
p=p->Lchild;
}
if(!Empty(s)){
p=pop(&s,p);
p=p->Rchild;
}
}
}
void midOrder(BTtree L){ //中序遍历
Sstack s;
BTtree p;
s=Init_Sstack();
p=L;
while(p!=NULL||!Empty(s)){
while(p!=NULL){
Push(&s,p);
p=p->Lchild;
}
if(!Empty(s)){
p=pop(&s,p);
printf("%c",p->data);
p=p->Rchild;
}
}
}
void BackOrder(BTtree L) //后序遍历
{
Sstack s;
BTtree p,q;
s = Init_Sstack();p = L;q = NULL;
while (p != NULL||!Empty(s))
{
while (p != NULL)
{
Push(&s, p);
p = p->Lchild;
}
if (!Empty(s))
{
p = top(&s);
if (p->Rchild == NULL || p->Rchild == q)
{
p = pop(&s, p);
printf("%c", p->data);
q = p;
p = NULL;
}
else
p = p->Rchild;
}
}
}