POJ 2255 经典的重建二叉树

14 篇文章 0 订阅

根据前序遍历和中序遍历构造后序遍历。

根据树的递归性。其实每次我们找根就OK了,剩下的递归来做。

根据前序找到根,根据中序找到左子树和右子树。然后递归的进行。

#include <stdio.h>
#include <iostream>
#include <queue>
#include <algorithm>
#include <map>
#include <vector>
#include <cmath>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <fstream>
#include <set>
#include <stack>
using namespace std;

#define READ freopen("acm.in","r",stdin)
#define WRITE freopen("acm.out","w",stdout)
#define ll long long
#define ull unsigned long long 
#define PII pair<int,int>
#define PDI pair<double,int>
#define PDD pair<double,double>
#define MII map<int,int>::iterator 
#define fst first
#define sec second
#define MS(x,d) memset(x,d,sizeof(x))
#define INF 0x3f3f3f3f
#define ALL(x) x.begin(),x.end()
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define ROOT 0,n-1,1
#define PB push_back
#define FOR(a,b,c) for(int a=b;a<c;a++)
#define MOD 706679
#define keyTree (ch[ ch[root][1] ][0])
#define MAX 200000

char qian[500];
char zhong[500];
void dfs(int ql,int qr,int zl,int zr)
{
    if(ql>qr||zl>zr)
        return ;
    if(ql==qr)
    {
        cout<<qian[ql];
        return ;
    }
    char rt=qian[ql];
    int p=0;
    int cnt=0;
    for(int i=zl;i<=zr;i++)
    {
        if(zhong[i]==rt)
        {
            p=i;
            break;
        }
        cnt++;
    }
    if(ql+cnt>=ql+1)
        dfs(ql+1,ql+cnt,zl,zl+cnt-1);
    if(qr>=ql+cnt+1)
        dfs(ql+cnt+1,qr,zl+cnt+1,zr);
    cout<<rt;
}   

int main()
{
    while(scanf("%s%s",qian,zhong)!=EOF)
    {
        int len=strlen(qian);
        //cout<<len<<endl;
        dfs(0,len-1,0,len-1);
        cout<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值