0
点赞
收藏
分享

微信扫一扫

【PAT甲级】1020 Tree Traversals(已知树的中序+后序遍历输出层序遍历)

北邮郭大宝 2022-03-30 阅读 21
#include <bits/stdc++.h>

using namespace std;

const int N = 40;
int n;
int post[N], in[N];
unordered_map<int, int> l, r, pos;
vector<int> res;

int buildTree(int il, int ir, int pl, int pr)
{
    int root = post[pr];
    int k = pos[root];
    if(k > il) l[root] = buildTree(il, k - 1, pl, k - 1 - il + pl);
    if(k < ir) r[root] = buildTree(k + 1, ir, k - 1 - il + pl + 1, pr - 1);

    return root;
}

void bfs(int u)
{
    queue<int> q;
    q.push(u);
    while(q.size())
    {
        auto t = q.front();
        res.push_back(t);
        q.pop();
        if(l.count(t)) q.push(l[t]);
        if(r.count(t)) q.push(r[t]);
    }
}

int main()
{
    cin >> n;
    for(int i = 0; i < n; i++) cin >> post[i];
    for(int i = 0; i < n; i++) 
    {
        cin >> in[i];
        pos[in[i]] = i; 
    }
    
    int root = buildTree(0, n - 1, 0, n - 1);

    bfs(root);

    cout << res[0];
    for(int i = 1; i < res.size(); i++) cout << ' ' << res[i];
    cout << endl;
}

在这里插入图片描述

举报

相关推荐

二叉树的先序 中序 后序遍历

0 条评论