zoukankan      html  css  js  c++  java
  • pat 团体赛练习题集 L2-006. 树的遍历

    给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。

    输入格式:

    输入第一行给出一个正整数N(<=30),是二叉树中结点的个数。第二行给出其后序遍历序列。第三行给出其中序遍历序列。数字间以空格分隔。

    输出格式:

    在一行中输出该树的层序遍历的序列。数字间以1个空格分隔,行首尾不得有多余空格。

    输入样例:
    7
    2 3 1 5 7 6 4
    1 2 3 4 5 6 7
    
    输出样例:
    4 1 6 3 5 7 2
    

    题目很简单,就是已知后序中序求层序。其实和已知后序中序求前序一样的做法,只要将求得的序列用数组保存起来,用数组存起来的序列就是层序遍历的结果。

    //Asimple
    #include <bits/stdc++.h>
    #define INF 1e10
    #define mod 10007
    #define swap(a,b,t) t = a, a = b, b = t
    #define CLS(a, v) memset(a, v, sizeof(a))
    #define debug(a)  cout << #a << " = "  << a <<endl
    #define abs(x) x<0?-x:x
    using namespace std;
    typedef long long ll;
    const int maxn = 35;
    int n;
    int pos[maxn], in[maxn];
    vector<int> res(10000, -1);
    
    void solve(int root, int s, int e, int index) {
        if( s > e ) return ;
        int i = s;
        while( i<e && in[i]!=pos[root])i++;
        res[index] = pos[root];
        solve(root-1-e+i, s, i-1, index*2+1);
        solve(root-1, i+1, e, index*2+2);
    }
    
    void input() {
        cin >> n;
        for(int i=0; i<n; i++) cin >> pos[i] ;
        for(int i=0; i<n; i++) cin >> in[i];
        solve(n-1, 0, n-1, 0);
        int cnt = 0;
        for(int i=0; i<res.size(); i++) {
            if( res[i]!=-1 && cnt!=n-1 ) {
                printf("%d ", res[i]);
                cnt ++;
            } else if(res[i]!=-1){
                printf("%d
    ", res[i]);
                break;
            }
        }
    }
    
    int main() {
        input();
        return 0;
    }
    低调做人,高调做事。
  • 相关阅读:
    在UNICODE编码格式下, CString 转换为 char* :
    inet_ntop(), inet_pton(), htonl(), ntohl()
    'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)'
    NMAKE:fatal error U1077.“...cl.exe” return code 0xc0000135
    拷贝(复制)构造函数和赋值函数
    GIS 地图中术语解释
    Linux 下防火墙端口设置
    LInux 下安装jdk
    ln 命令
    zip命令
  • 原文地址:https://www.cnblogs.com/Asimple/p/6475905.html
Copyright © 2011-2022 走看看