树的重建uva536

给出先序遍历和中序遍历求后续遍历

    #include<stdio.h>  
    #include<string.h>  
      
    void build(int n, char *s1, char *s2, char *s) {  
        if(n <= 0)  
            return;  
        int p = strchr(s2, s1[0]) - s2;  
        build(p, s1+1, s2, s);  
        build(n-1-p, s1+p+1, s2+p+1, s+p);  
        s[n-1] = s1[0];  
    }  
      
    int main() {  
        char str1[30], str2[30];  
        char ans[30];  
        int len;  
        while(scanf("%s%s", str1, str2) != EOF) {  
            len = strlen(str1);  
            build(len, str1, str2, ans);  
            ans[len] = '\0';  
            puts(ans);  
        }  
        return 0;  
    }  


#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
string befor,inor,ans;
int lenb,leni;
void post(int lb,int li,int ri)
{
    if(lb>=lenb||li>=leni||ri>>leni)return;
    if(li==ri){ans+=befor[lb];return;}
    int j;
    for(j=li;j<=ri;j++)
        if(inor[j]==befor[lb])break;
    post(lb+1,li,j-1);
    post(lb+1+j,j+1,ri);
    ans+=befor[lb];
}
int main()
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt","r",stdin);
    #endif

    while(cin>>befor>>inor)
    {
        ans.clear();
        lenb=befor.size(),leni=inor.size();
        post(0,0,leni-1);
        ans+='\0';
        cout<<ans<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值