由前中序求后序
思路:
1 确定根,确定左子树,确定右子树。
2 在左子树中递归。
3 在右子树中递归。
4 打印当前根。
#include<stdio.h>
#include<string.h>
#define max 100
void rebuild(char *pre,char *in,int len);
int main()
{
char pre[max],in[max];
while(~scanf("%s%s",pre,in))
{
rebuild(pre,in,strlen(pre));
printf("\n");
}
return 0;
}
void rebuild(char *pre,char *in,int len)
{
char root1;
root1=*pre;
if(len==0)
return ;
int root;
for(root=0;root<len;root++)
if(in[root]==root1)//区分左右子树
break;
rebuild(pre+1,in,root);//左子树
rebuild(pre+root+1,in+root+1,len-root-1);//柚子树,roo+1为左子树的长度
printf("%c",root1);
}
知中后序求前原理:
1 确定根,确定左子树,确定右子树。
2 在左子树中递归。
3 在右子树中递归。
4 打印当前根。
#include<stdio.h>
#include<string.h>
#define max 100
void rebuild(char *post,char *in,int len);
int main()
{
char post[max],in[max];
while(~scanf("%s%s",post,in))
rebuild(post,in,strlen(in));
return 0;
}
void rebuild(char *post,char *in,int len)
{
char root1;
if(len==0)//特殊情况
return ;
root1=*(post+len-1);//最后一个就是根,后基本规则
printf("%c",root1);
int root;
for(root=0;root<len;root++)
if(in[root]==root1)
break;
rebuild(post,in,root);//左子树
rebuild(post+root,in+root+1,len-root-1);//右子树
}