修水一中 零班:设计一个程序,根据二叉树的先根序列和对称序序列创建一棵用左、右指针表示的二叉树.

来源:百度文库 编辑:中科新闻网 时间:2024/05/10 12:27:22

typedef struct BiNode{
char data;
struct BiNode *lchild,*rchild;
}BiTree;
BiTree *restore(char *ppos,char *ipos,int n)
{
BiTree *ptr;
char *rpos;
int k;
if(n<=0) return NULL;
ptr=(BiTree*)malloc(sizeof(BiNode));
ptr->data=*ppos;
for(rpos=ipos;rposif(*rpos==*ppos)
break;
k=rpos-ipos;
ptr->lchild=restore(ppos+1,ipos,k);
ptr->rchild=restore(ppos+k+1,rpos+1,n-k-1);
return ptr;
}
void postorder(BiTree *ptr){
if(ptr!=NULL)
{
postorder(ptr->lchild);
postorder(ptr->rchild);
printf("%c\\t",ptr->data);
}
}
void main()
{
BiTree *root;
char inod[10]={\'D\',\'B\',\'G\',\'E\',\'H\',\'J\',\'A\',\'C\',\'I\',\'F\'};//中序
char pred[10]={\'A\',\'B\',\'D\',\'E\',\'G\',\'H\',\'J\',\'C\',\'F\',\'I\'};//前序
root=restore(pred,inod,strlen(pred));
postorder(root);
}