已知一颗二叉树S的前序遍历和中序遍历序列,请编程输出二叉树S的后序遍历序列
eg:pred【】前序:A,B,D,E,C,F,G
inod【】中序:D,B,E,A,C,G,F;
后序D,E,B,G,F,C,A;
#include<stdio.h>
#include<string.h>
int find(char c,char A[],int s,int e)
{
int i;
for(i=s;i<=e;i++)
if(A[i]==c)
return i;
}
void behind_1(char pre[],int pre_s,int pre_e,char in[],int in_s,int in_e)
{
char c;
int k;
if(in_s>in_e)return;
if(in_s==in_e)
{
printf("%c",in[in_s]);
return;
}
c=pre[pre_s];
k=find(c,in,in_s,in_e);//求根,返回pre中的下标
behind_1(pre,pre_s+1,pre_s+k-in_s,in,in_s,k-1);//递归左子树,利用正常的求后序方法,先以前序第一个为根,再到中序中去切割
behind_1(pre,pre_s+k-in_s+1,pre_e,in,k+1,in_e);//递归右子树
printf("%c",c);
}
int main()
{
char pre[]="ABDECFG";
char in[]="DBEACGF";
behind_1(pre,0,strlen(pre)-1,in,0,strlen(in)-1);
printf("\n");
}