#include
#include
#include
#define SIZE 40
typedef struct Tnode *BinTree;
typedef struct Tnode
{
int data;
BinTree pright;
BinTree pleft;
}NODE;
typedef struct Snode
{
//这边数组时结构指针数组,不是结构
//搞明白这个走了点弯路;
struct Tnode * arry[SIZE];
int MAXSIZE;
int top;
}*stack, SNODE;
//Tree operations;
BinTree creat_tree(void);
void free_tree(BinTree *T);
void midtraversal(BinTree T);
void pretraversal(BinTree T);
//栈的操作
stack creat_stack();
bool push(stack S, BinTree T);
bool Isstackempty(stack S);
BinTree pop(stack S);
int main(void)
{
BinTree T = creat_tree();
printf(“xianxu:\n”);
pretraversal(T);
printf(“houxu:\n”);
midtraversal(T);
free_tree(&T);
return 0;
}
BinTree creat_tree(void)
{
BinTree pa = (BinTree)malloc(sizeof(NODE));
BinTree pb = (BinTree)malloc(sizeof(NODE));
BinTree pc = (BinTree)malloc(sizeof(NODE));
BinTree pd = (BinTree)malloc(sizeof(NODE));
BinTree pe = (BinTree)malloc(sizeof(NODE));
BinTree pf = (BinTree)malloc(sizeof(NODE));
BinTree pg = (BinTree)malloc(sizeof(NODE));
BinTree ph = (BinTree)malloc(sizeof(NODE));
BinTree pi = (BinTree)malloc(sizeof(NODE));
BinTree pj = (BinTree)malloc(sizeof(NODE));
BinTree pk = (BinTree)malloc(sizeof(NODE));
pa->data = 'A';
pb->data = 'B';
pc->data = 'C';
pd->data = 'D';
pe->data = 'E';
pf->data = 'F';
pg->data = 'G';
ph->data = 'H';
pi->data = 'I';
pj->data = 'J';
pk->data = 'K';
pa->pleft = pb;
pa->pright = pc;
pb->pleft = pd;
pb->pright = pe;
pc->pright = pf;
pc->pleft = NULL;
pd->pleft = pg;
pd->pright = ph;
pe->pright = pi;
pe->pleft = NULL;
pf->pleft = pj;
pf->pright = pk;
pg->pleft = NULL;
pg->pright = NULL;
ph->pright =NULL;
ph->pleft =NULL;
pi ->pleft =NULL;
pi->pright =NULL;
pj ->pleft =NULL;
pj->pright =NULL;
pk ->pleft =NULL;
pk->pright =NULL;
return pa;
}
void pretraversal(BinTree T)
{
stack S = creat_stack();
BinTree work = T;
while (work || !Isstackempty(S))
{
while (work)
{
push(S, work);
printf("%3c\n", work->data);
work = work->pleft;
}
work = pop(S);
work = work->pright;
}
}
void midtraversal(BinTree T)
{
stack S = creat_stack();
BinTree work = T;
while (work || !Isstackempty(S))
{
while (work)
{
push(S, work);
work = work->pleft;
}
work = pop(S);
printf("%3c\n", work->data);
work = work->pright;
}
}
void free_tree(BinTree *T)
{
if(*T)
{
free_tree( &((*T)->pleft));
free_tree(&((*T)->pright));
free(*T);
*T = NULL;
}
}
stack creat_stack()
{
//stack里的是Bintree的指针数组;
stack tmp = (stack)malloc(sizeof(SNODE));
tmp->MAXSIZE =SIZE;
tmp ->top = -1;
return tmp;
}
bool Isstackempty(stack S)
{
if (S->top == -1)
{
return true;
}
else
{
return false;
}
}
BinTree pop(stack S)
{
if (Isstackempty(S))
{
return NULL;
}
else
{
return S->arry[(S->top)–];
}
}
bool push(stack S, BinTree T)
{
if (S->top == S->MAXSIZE-1)
{
return false;
}
S->arry[ ++(S->top)] = T;
return true;
}