zoukankan      html  css  js  c++  java
  • PTA1020

    题意

    给出n个点的后序和中序,让我们输出层序遍历顺序,末尾没有空格。

    根据样例给出的后序和中序,所构建的二叉树如图所示:

    所以容易得知,层序遍历为:4 1 6 3 5 7 2

    思路

    模板题。通过map将前序遍历的id与层序遍历的level相对应。

    注意

    1. 如果题目问的是求前序,那么id就不用记录了

    2. vector post,in; 可以写成 int post[40],in[40]; ,这样main函数里面就不用resize了

    3. 但是我不太明白的一点就是为什么vector定义之后不resize就会错误??!

    AC代码

    #include<iostream>
    #include<string>
    #include<stdio.h>
    #include<algorithm>
    #include<map>
    #include<vector>
    #include<stack>
    #include<queue>
    using namespace std;
    typedef long long ll;
    #define inf 0x3f3f3f3f
    
    vector<int> post,in; // 后序 中序
    map<int,int> level;
    
    void pre(int root,int s,int e,int id)
    {
        if(s>e) return;
        int i=s;
        while(i<e&&in[i]!=post[root]) i++; // 让i在中序中找到根结点
        level[id]=post[root];
        //cout<<"**"<<post[root]<<"**"; // 如果已知后序中序求前序的话,就在这边输出前序就好了
        pre(root-(e-i+1),s,i-1,2*id+1);
        // 左子树在后序中的根结点=当前根结点-(右子树的个数+1)
        pre(root-1,i+1,e,2*id+2);
        // 右子树的根结点=当前根结点的前一个结点
    }
    
    int main()
    {
        int n;
        cin>>n;
        post.resize(n),in.resize(n);
        for(int i=0;i<n;i++)
            cin>>post[i];
        for(int i=0;i<n;i++)
            cin>>in[i];
        pre(n-1,0,n-1,0);
    
        auto it=level.begin();
        cout<<it->second;
        while(++it!=level.end())
            cout<<" "<<it->second;
    
    // 如果没有格式要求的话,可以这样写
    //    for(auto&it:level) // 输出
    //        cout<<it.second<<" ";
    //    cout<<endl;
        return 0;
    }
    
  • 相关阅读:
    时间戳 时间 相互转换
    CS Academy Remove Update
    一周水题集锦 2017 9.4
    计蒜客 16877 卡牌游戏
    计蒜客 16876 韩梅梅的抽象画
    九度OJ 题目1534:数组中第K小的数字
    CS Academy Switch the Lights
    CF AIM Tech Round 4 C. Sorting by Subsequences
    CF Round 430 C. Ilya And The Tree
    CS Academy Round 44 Check DFS
  • 原文地址:https://www.cnblogs.com/OFSHK/p/14491386.html
Copyright © 2011-2022 走看看