1127 ZigZagging on a Tree (30 分)【难度: 一般 / 知识点: 根据中序遍历 后序遍历建树】

在这里插入图片描述
https://pintia.cn/problem-sets/994805342720868352/problems/994805349394006016
PAT甲级中算是很传统的题了,就是建树,然后遍历即可。

#include<bits/stdc++.h>
using namespace std;
const int N=1e2+10;
int a[N],b[N],n;
unordered_map<int,int>l,r,hush;
int build(int l1,int r1,int l2,int r2)
{
    
    
    int root=b[r1];
    int k=hush[root];
    if(k<r2) r[root]=build(r1+k-r2,r1-1,k+1,r2);
    if(k>l2) l[root]=build(l1,r1+k-r2-1,l2,k-1);
    return root;
}
void solve()
{
    
    
    vector<int>ve[N];
    int deep=0;
    queue<pair<int,int>>q; q.push({
    
    b[n],1});
    while(q.size())
    {
    
    
        auto t=q.front(); q.pop();
        int u=t.first,len=t.second;
        ve[len].push_back(u);
        if(l[u]) q.push({
    
    l[u],len+1});
        if(r[u]) q.push({
    
    r[u],len+1});
        deep=max(deep,len);
    }
    int cnt=0;
    for(int i=1;i<=deep;i++)
    {
    
    
        if(i&1) reverse(ve[i].begin(),ve[i].end());
        for(int j=0;j<ve[i].size();j++) 
        {
    
    
            cnt++;
            cout<<ve[i][j];
            if(cnt!=n) cout<<" ";
        }
    }
}
int main(void)
{
    
    
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i],hush[a[i]]=i;
    for(int i=1;i<=n;i++) cin>>b[i];
    build(1,n,1,n);
    solve();
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_46527915/article/details/121523950