PAT甲级真题1020树的遍历

哈希表可以在O(1)的时间内找到后序遍历的根结点在中序遍历的位置

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


using namespace std;

const int N = 40;

int n;
int postorder[N], inorder[N];
unordered_map<int, int> l, r, pos;//用哈希表存左儿子和右儿子,和映射


//中序遍历的左端点和右端点,后序遍历的左端点和右端点
int build(int il, int ir, int pl, int pr)
{
    int root = postorder[pr];//根节点是后序遍历的最后一个点
    int k = pos[root];//找到根节点在中序遍历的下标
    if (il < k) l[root] = build(il, k - 1, pl, pl + (k - 1 - il));
    if (k < ir) r[root] = build(k + 1, ir, pl + (k - 1 - il) + 1, pr - 1);
    return root;//返回当前这个子树的根节点
}

void bfs(int root)
{
    queue<int>q;
    q.push(root);
    while(q.size())
    {
        auto t=q.front();
        q.pop();
        cout<<t<<" ";
        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 >> postorder[i];//后序遍历
    for (int i = 0; i < n; i ++ )
    {
        cin >> inorder[i];//中序遍历
        pos[inorder[i]] = i;//映射,存中序遍历每个值的下标是多少
    }

    int root = build(0, n - 1, 0, n - 1);//重建二叉树,中序遍历的下标是0到n-1,后序遍历的下标也是0到n-1

    bfs(root);

    return 0;
}

//需要在中序遍历里找到某个值的位置,因此可以用哈希表存中序遍历每个值的下标是多少

输出左子树和右子树

    for(auto &pl:l)//pr是名字,随便取
    {
        cout<<pl.first<<"->"<<pl.second<<endl;
    }
    cout<<endl;
    for(auto &pr:r)//pr是名字,随便取
    {
        cout<<pr.first<<"->"<<pr.second<<endl;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值