zoukankan      html  css  js  c++  java
  • L2-006 树的遍历

      

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

    输入格式:

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

    输出格式:

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

    输入样例:

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

    输出样例:

    4 1 6 3 5 7 2


    b标准的二叉树重建 必须熟练掌握
    #include<bits/stdc++.h>
    using namespace std;
    //input by bxd
    #define rep(i,a,b) for(int i=(a);i<=(b);i++)
    #define repp(i,a,b) for(int i=(a);i>=(b);i--)
    #define RI(n) scanf("%d",&(n))
    #define RII(n,m) scanf("%d%d",&n,&m)
    #define RIII(n,m,k) scanf("%d%d%d",&n,&m,&k)
    #define RS(s) scanf("%s",s);
    #define LL long long
    #define pb push_back
    #define fi first
    #define REP(i,N)  for(int i=0;i<(N);i++)
    #define CLR(A,v)  memset(A,v,sizeof A)
    ///////////////////////////////////
    #define inf 0x3f3f3f3f
    #define N 400000+5
    int zhong [N];
    int hou[N];
    int l[N];
    int r[N];
    
    int build(int l1,int l2,int r1,int r2)
    {
        if(l1>l2||r1>r2)return 0;
        int root=hou[r2];
        int p=l1;
        while(zhong[p]!=root)p++;
        int cnt=p-l1;
        l[root]=build(l1,l1+cnt-1,r1,r1+cnt-1);
        r[root]=build(l1+cnt+1,l2,r1+cnt,r2-1);
        return root;
    }
    void bfs(int root)
    {
        queue<int>q;
        q.push(root);
        int first=1;
        while(!q.empty())
        {
            int u=q.front();q.pop();
            if(first){first=0;printf("%d",u);}
            else printf(" %d",u);
            if(l[u])q.push(l[u]);
            if(r[u])q.push(r[u]);
        }
    }
    
    int main()
    {
        int n;
        RI(n);
        rep(i,1,n)
        RI(hou[i]);
        rep(i,1,n)
        RI(zhong[i]);
        int root=hou[n];
        build(1,n,1,n);
        bfs(root);
        return 0;
    }
    View Code


  • 相关阅读:
    Django(进阶篇)之model
    RabbitMQ、Memcache、Redis(队列、缓存)
    AJAX总结
    数据库 MySql(二)
    Python操作mysql之SQLAchemy(ORM框架)
    Python操作Mysql
    Tornado框架
    Ubuntu 出现未定义的 curl_init 错误
    ubuntu下apache配置https且强制http转向为https 腾讯云
    Git fetch
  • 原文地址:https://www.cnblogs.com/bxd123/p/10569343.html
Copyright © 2011-2022 走看看