• 树的遍历


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

    输入格式:

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

    输出格式:

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

    输入样例:

    7
    2 3 1 5 7 6 4
    1 2 3 4 5 6 7
    
     

    输出样例:

    4 1 6 3 5 7 2



    #include <bits/stdc++.h>
    using namespace std;
    const int maxn = 1e5 + 10;
    int n,mid[maxn],beh[maxn];
    
    struct node{
        int l,r;
    }tree[maxn];
    
    int build(int la,int ra,int lb,int rb){//分别表示中序和后序
        if(la > ra) return 0;
        int root = beh[rb];
        int p = la;
        while(mid[p] != root)
            p++;
        int t = p - la;
        tree[root].l = build(la,p - 1,lb,lb + t - 1);
        tree[root].r = build(p + 1,ra,lb + t,rb - 1);
        return root;
    }
    vector<int> ve;
    queue<int> que;
    void bfs(int x){
        que.push(x);
        while(!que.empty()){
            int tp = que.front();
            que.pop();
            ve.push_back(tp);
            if(tree[tp].l)
                que.push(tree[tp].l);
            if(tree[tp].r)
                que.push(tree[tp].r);
        }
    }
    int main(){
        //freopen("in","r",stdin);
        ios::sync_with_stdio(0);
        cin >> n;
        for(int i = 1; i <= n; i++) cin >> beh[i];
        for(int i = 1; i <= n; i++) cin >> mid[i];
        build(1,n,1,n);
        bfs(beh[n]);
        for(int i = 0; i < ve.size(); i++){
            if(i) cout << " " << ve[i];
            else cout << ve[i];
        }
        return 0;
    }
    View Code
  • 相关阅读:
    hdu2795-Billboard(线段树应用好题)
    AC自动机模板
    kmp模板
    字符串Hash模板
    (可持久化)带修莫队的实现方法
    HZNU1544众数问题
    NOIP2006提高组第二题-金明的预算方案
    Python学习笔记
    (模板)唯一分解定理
    Java 7 源码学习系列(二)——Enum
  • 原文地址:https://www.cnblogs.com/xcfxcf/p/12333734.html
Copyright © 2020-2023  润新知