前中序求后序

a b d  f g  e  h i  c  k j: 前序

f d  g  b h e  i  a k  c j:中序

0 1 2 3  4 5  6 7 8 9 10

用前序的首字母 将中序分割成两段 分别对应左右子树

关键在于如何得到这两段 很简单 :在中序里 a的序号为7,从而0-7 为左子树,这一段相应在前序中序号为 1-8(前点虽然不同,但长度相同)

  b d f g e h i  : 前序

f d g b h e i   :中序

char post[1000];
char pre[1000];
char mid[1000];
int getroot(char r)
{
int i=0;
while(mid[i]!='\0'&& mid[i]!=r)
i++;
if(mid[i]!='\0')
return i;
else return -1;
}
void getpost(int pl,int pr,int ml,int mr,int id)
{
if(pl>pr||ml>mr) return;
cout<<"getpost("<<pl<<","<<pr<<","<<ml<<","<<mr<<")"<<endl;
char root=pre[pl];
int rid=getroot(root);
getpost(pl+1,pl+rid-ml,ml,rid-1,id-(mr-rid)-1);
getpost(pl+rid-ml+1,pr,rid+1,mr,id-1);
post[id]=root;

}

int main()
{
scanf("%s",pre);
scanf("%s",mid);
int len=strlen(pre);
getpost(0,len-1,0,len-1,len-1);

cout<<post<<endl;
system("pause");
return 0;
}

posted @ 2012-08-11 14:43  wuzhibin  阅读(191)  评论(0)    收藏  举报