给出前序和中序,求后序遍历
思路:
由前序排列可以得到主树的根,由中序排列可以区分出左子树和右子树。
主要分两步:由前序和中序还原树,在后序遍历整棵树,易知,后序遍历函数肯定是递归的。
函数
名称 | 传入 | 传出 | 功能 |
aft() | 树 | 后序遍历树并打印出结果 | |
build() | 前序和中序遍历结果 | 树 | 由前序和中序还原树 |
树结点申请内存空间时若不知道如何动态申请或释放内存,可以静态申请内存,函数为
create() | 树 | 初始化结点,左右子树赋为空 |
#include<stdio.h>
#include<string.h>
struct Node{
Node *ltre;
Node *rtre;
char c;
}buf[50];
char pre[30],mid[30];
int loc;
Node *create(){
buf[loc].ltre=buf[loc].rtre=NULL;
return &buf[loc++];
}
void aft(Node *t){
if(t->ltre!=NULL){
aft(t->ltre);
}
if(t->rtre!=NULL){
aft(t->rtre);
}
printf("%c",t->c);
}
Node *build(int s1,int e1,int s2,int e2){//前序遍历从s1到e1,中序遍历从s2到e2
Node *tre=create();
tre->c=pre[s1];
int rtx;
for(int i=s2;i<=e2;i++){
if(pre[s1]==mid[i]){//在中序遍历中找到了根
rtx=i;
break;
}
}
if(rtx!=s2){//有左子树
tre->ltre=build(s1+1,s1+rtx-s2 ,s2,rtx-1);
}
if(rtx!=e2){//有右子树
tre->rtre=build(s1+rtx-s2+1,e1,rtx+1,e2);
}
return tre;
}
int main(){
while(scanf("%s",&pre)!=EOF){
scanf("%s",&mid);
loc=0;
int l1=strlen(pre);
int l2=strlen(mid);
Node *t=build(0,l1-2,0,l2-1);
aft(t);
printf("\n");
}
return 0;
}