由二叉树先序序列和中序序列求后序序列的C语言算法

#include
#include
#include
#define NULL 0


struct btree
{
char num;
struct btree* lchild;
struct btree* rchild;
};
struct stack
{
struct btree* base;
struct btree* top;
int stacksize;
};


int main()
{
struct btree *create(char *arrayfirst,char *arraymiddle,int len);
void followvisit(struct btree *bt);
char arrayfirst[20];
char arraymiddle[20];
int len;
struct btree *bt;
scanf("%s",arrayfirst);
scanf("%s",arraymiddle);
len=strlen(arrayfirst);
bt=create(arrayfirst,arraymiddle,len);
followvisit(bt);
printf("\n");
return 0;
}
struct btree *create(char *arrayfirst,char *arraymiddle,int len)
{
struct btree *bt;
bt=(struct btree *)malloc(sizeof(struct btree));
if(len==1)
{
bt->num=*arrayfirst;
bt->lchild=NULL;
bt->rchild=NULL;
return bt;
}
else
{
int count=1,i=0;
while(*arrayfirst!=*(arraymiddle+i))
{
i++;
count++;
}
bt->num=*arrayfirst;
if(count==1)
bt->lchild=0;
else
bt->lchild=create(arrayfirst+1,arraymiddle,count-1);
if(count==len)
bt->rchild=0;
else
bt->rchild=create(arrayfirst+count,arraymiddle+count,len-count);//这句是关键,计数器的作用很重要
return bt;
}
}
//void followvisit(struct btree *bt)
//{//后序遍历的递归算法
// if(!bt->lchild&&!bt->rchild)
// printf("%c",bt->num);
// else
// {
// if(bt->lchild)
// followvisit(bt->lchild);
// if(bt->rchild)
// followvisit(bt->rchild);
// printf("%c",bt->num);
// }
//}
void followvisit(struct btree *bt)
{//后序遍历的非递归算法
struct btree *p,array[20];
int top=0;
p=bt;
while(top>=0||p->num)
{
if(p->num)
{
array[top++]=*p;
p=p->lchild;
}
else
{
p=&array[--top];
if(!p->rchild)
{
printf("%c",p->num);
top--;
p=array[top];//?????????????????
}
else
{
top++;
p->rchild;
}
}
}
}



你可能感兴趣的:(由二叉树先序序列和中序序列求后序序列的C语言算法)