由二叉樹先序序列和中序序列求後序序列的C語言算法

#include
#include<stdlib.h>
#include<string.h>
#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;
}
}
}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章