Description
已知一棵二叉树的前序序列和中序序列分别存于两个一维数组中,试编写算法建立该二叉树的二叉链表
Input
分两行分别输入一棵二叉树的前序序列和中序序列。
Output
输出该二叉树的后序序列。
SampleInput ABDFGCEH
BFDGACEH
SampleOutput FGDBHECA
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
typedef struct node
{
char data;
struct node*lchild;
struct node*rchild;
}BiTNode,*BiTree;
void midprecreat(BiTree*root,char mid[],char pre[],int lm,int rm,int lp,int rp)
{
*root=(BiTree)malloc(sizeof(BiTNode));
(*root)->data=pre[lp];
(*root)->lchild=NULL;
(*root)->rchild=NULL;
int pos=lm;
while(mid[pos]!=pre[lp])
pos++;
int childlen=pos-lm;//用来控制子树在字符串中的范围
if(pos>lm)//有左子树,递归创建
midprecreat((&((*root)->lchild)),mid,pre,lm,pos-1,lp+1,lp+childlen);
if(pos<rm)//有右子树,递创建
midprecreat((&((*root)->rchild)),mid,pre,pos+1,rm,lp+childlen+1,rp);
}
void print(BiTree p)
{ if(p != NULL)
{
print(p->lchild); //遍历左子树
print(p->rchild); //遍历右子树
printf("%c",p->data); //输出该结点
}
}
int main()
{
char pre[100]; //存储先序序列
char mid[100]; //存储中序序列
int n;
BiTree root;
gets(pre);
n=strlen(pre);
gets(mid);
midprecreat(&root,mid,pre,0,n-1,0,n-1);
print(root);
return 0;
}