小白书之根据二叉树的先序遍历和中序遍历得出后序遍历

本文介绍了一种通过后序和中序遍历序列来重构先序遍历序列的算法。通过理解函数递归调用过程,我们能够编写出高效且易于理解的代码实现。示例代码使用了标准C++库函数,并提供了详细的注释以辅助理解。

可以类似的写一下根据后序遍历和中序遍历得出先序遍历,只要理解函数递归调用的过程就很好写,

函数递归调用的过程只要记住一句话,只有递归返回条件满足才会返回,只有当前的所有问题都解决了,

才会递归回到上一层。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<string>
#include<cctype>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<stack>
#define LL __int64
using namespace std;
const double pi=4*atan(1.0);
const int MAXN=1001;
void build(int n,char *s1,char *s2,char *s)
{
    if(n<=0) return;
    int p=strchr(s2,s1[0])-s2;
   // cout<<p<<endl;
    //s[0]=s1[n-1];
    build(p,s1+1,s2,s);
   // cout<<"diaoyong1"<<endl;
    build(n-p-1,s1+p+1,s2+p+1,s+p);
   // cout<<"diaoyong2"<<endl;
   // cout<<s1[0]<<endl;
    s[n-1]=s1[0];
}
int main()
{
    char s1[MAXN],s2[MAXN],ans[MAXN];
    while(scanf("%s%s",s1,s2)==2)
    {
        int n=strlen(s1);
        build(n,s1,s2,ans);
        ans[n]='\0';
        cout<<ans<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值