二叉树的遍历

给出前序和中序,求后序遍历

思路:

由前序排列可以得到主树的根,由中序排列可以区分出左子树和右子树。

主要分两步:由前序和中序还原树,在后序遍历整棵树,易知,后序遍历函数肯定是递归的。

函数

名称传入传出功能
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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值