1020 Tree Traversals (25 分) 难度: 中 / 知识点: 哈希表建树 遍历树

Posted 辉小歌

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1020 Tree Traversals (25 分) 难度: 中 / 知识点: 哈希表建树 遍历树相关的知识,希望对你有一定的参考价值。


https://pintia.cn/problem-sets/994805342720868352/problems/994805485033603072
第一步: 建树
第二步: 遍历树

#include<bits/stdc++.h>
using namespace std;
const int N=1e3+10;
unordered_map<int,int>l,r,pos;
int a[N],b[N],n;
int build(int l1,int r1,int l2,int r2)
{
    int root=a[r2];//后序遍历的最后一个点一定是根
    int k=pos[root];//找到对应的中序遍历的位置
    if(l1<k) l[root]=build(l1,k-1,l2,k-l1+l2-1);//有左儿子
    if(r1>k) r[root]=build(k+1,r1,k-l1+l2-1+1,r2-1);//有有儿子
    return root;
}
void dfs(int root)
{
    queue<int>q; q.push(root);
    bool flag=false;
    while(q.size())
    {
        int t=q.front(); q.pop();
        if(flag) cout<<" ";
        cout<<t;
        flag=true;
        if(l.count(t)) q.push(l[t]);//有左儿子
        if(r.count(t)) q.push(r[t]);//有右儿子
    }
}
int main(void)
{
    cin>>n;
    for(int i=0;i<n;i++) cin>>a[i];
    for(int i=0;i<n;i++)
    {
        cin>>b[i];
        pos[b[i]]=i;
    }
    int root=build(0,n-1,0,n-1);// 中序遍历的左右区间  后序遍历的左右区间
    dfs(root);
}

以上是关于1020 Tree Traversals (25 分) 难度: 中 / 知识点: 哈希表建树 遍历树的主要内容,如果未能解决你的问题,请参考以下文章