L2-006. 树的遍历(由中根和后根序遍历建树)

题目链接:https://www.patest.cn/contests/gplt/L2-006

代码:

#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <queue>
#include <map>
#include <vector>
using namespace std;

const int maxn =30+5;

int a[maxn],b[maxn],lch[maxn],rch[maxn],n;

int build(int L1,int R1,int L2,int R2)//建树
{
    if(L1>R1)
        return 0;
    int root=a[R2];
    int p=L1;
    while(b[p]!=root)
        p++;
    int cnt=p-L1;
    lch[root]=build(L1,p-1,L2,L2+cnt-1);
    rch[root]=build(p+1,R1,L2+cnt,R2-1);
    return root;
}

vector <int>ans;

void dfs(int s)
{
    queue<int> q;
    ans.clear();
    q.push(s);
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        ans.push_back(u);
        if(lch[u]!=0)
           q.push(lch[u]);
        if(rch[u]!=0)
           q.push(rch[u]);
    }
    return;
}

int main()
{
    scanf("%d",&n);
    for(int i=0; i<n; i++)
        scanf("%d",&a[i]);//后序遍历
    for(int i=0; i<n; i++)
        scanf("%d",&b[i]);//后序遍历
    build(0,n-1,0,n-1);
    dfs(a[n-1]);
    vector<int>::iterator it;
       for( it = ans.begin(); it < ans.end()-1; it++ )
           printf("%d ",*it);
        printf("%d\n",ans.back());
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值