zoukankan      html  css  js  c++  java
  • L2-006 树的遍历 (25 分)

    链接:https://pintia.cn/problem-sets/994805046380707840/problems/994805069361299456


    题目:

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

    输入格式:

    输入第一行给出一个正整数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 <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cmath>
    #include <string>
    #include <cstring>
    #include <algorithm>
    #include <vector>
    #include <queue>
    
    using namespace std;
    typedef long long ll;
    typedef unsigned long long ull;
    const int inf=0x3f3f3f3f;
    const int maxn=50;
    int n;
    int mid[maxn],po[maxn];
    
    struct node{
        int l,r;
    }T[maxn];
    
    int mid_po_build(int la,int ra,int lb,int rb){
        if(la>ra) return 0;
        int rt=po[rb];
        int p1=la,p2;
        while(mid[p1]!=rt) p1++;
        p2=p1-la;
        T[rt].l=mid_po_build(la,p1-1,lb,lb+p2-1);
        T[rt].r=mid_po_build(p1+1,ra,lb+p2,rb-1);
        return rt;
    }
    
    void dfs(int rt){
        queue<int>Q;
        vector<int>v;
        Q.push(rt);
        while(!Q.empty()){
            int w=Q.front();
            Q.pop();
            v.push_back(w);
            if(T[w].l!=0) Q.push(T[w].l);
            if(T[w].r!=0) Q.push(T[w].r);
        }
        int len=v.size();
        for(int i=0;i<len;i++){
            printf("%d%c",v[i],i==(len-1)?'
    ':' ');
        }
    }
    
    int main(){
        scanf("%d",&n);
        for(int i=0;i<n;i++) scanf("%d",&po[i]);
        for(int i=0;i<n;i++) scanf("%d",&mid[i]);
        int rt=mid_po_build(0,n-1,0,n-1);
        dfs(rt);
        return 0;
    }
  • 相关阅读:
    Leetcode 121. Best Time to Buy and Sell Stock
    Leetcode 120. Triangle
    Leetcode 26. Remove Duplicates from Sorted Array
    Leetcode 767. Reorganize String
    Leetcode 6. ZigZag Conversion
    KMP HDU 1686 Oulipo
    多重背包 HDU 2844 Coins
    Line belt 三分嵌套
    三分板子 zoj 3203
    二分板子 poj 3122 pie
  • 原文地址:https://www.cnblogs.com/whdsunny/p/10620939.html
Copyright © 2011-2022 走看看