【PAT甲级】1020 Tree Traversals 树的遍历

题意 

给出后序,中序序列,求层次遍历

分析

1. 先建树,由后序,中序建立二叉树

2. 在bfs(root)

AC代码

#include <iostream>
#include <cstring>
#include <algorithm>
#include <unordered_map>
#include <queue>
#include <vector>

using namespace std;

const int N = 40;

int n;
vector<int> res;
int post[N], in[N];     //后序遍历,中序遍历
unordered_map<int, int> l, r, pos;  

int build(int il, int ir, int pl, int pr) //后序 后序 建树
{
    int root = post[pr]; // 找到根节点
    int k = pos[root];      //得到根节点在中序遍历中的下标

    //k大于il表示根节点左边还有节点,即当前根节点存在左子树,下同
    // 遍历左区间,并把左区间里的根节点存进 l[root]里, 即为 root 的左儿子
    // 同理右区间也是
    if (il < k) l[root] = build(il, k - 1, pl, pl + k - 1 - il);
    if (ir > k) r[root] = build(k + 1, ir, pl + k - il, pr - 1);

    return root;
}

void bfs(int root)                          //BFS用来层序遍历输出
{
    queue<int> q;
    q.push(root);
    while (q.size())
    {
        auto t = q.front();
        q.pop();
        res.push_back(t);
        //cout << t << ' ';  在这里直接输出也对 也可以用vector存起来, 一起输出也行

        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 = build(0, n - 1, 0, n - 1);   //参数为中序遍历区间和后序遍历区间
    bfs(root);

    cout << res[0];
    for(int i = 1; i < n; i ++ )
        cout << ' ' << res[i];
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值