zoukankan      html  css  js  c++  java
  • pat L2006. 树的遍历

    L2-006. 树的遍历

    时间限制
    400 ms
    内存限制
    65536 kB
    代码长度限制
    8000 B
    判题程序
    Standard
    作者
    陈越

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

    输入格式:

    输入第一行给出一个正整数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

    喜欢这个博主的代码:https://blog.csdn.net/qq_34594236/article/details/63273098
    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<queue>
    using namespace std;
    struct node
    {
        int num,left,right,h;
    }tree[35];
    int i,n,len;
    int a[35],b[35];
    int findroot(int root,int l,int r)
    {
        for(i=l;i<=r;i++)
          if(b[i]==root) return i;
    }
    void buildtree(int root,int l,int r,int u)
    {
        if(l>r) return;
        int k=findroot(a[root],l,r);
        if(l<k)
        {
            tree[++len].num=a[root-(r-k)-1];
            tree[len].h=tree[u].h+1;
            tree[u].left=len;
            buildtree(root-(r-k)-1,l,k-1,len);
        }
        if(r>k)
        {
            tree[++len].num=a[root-1];
            tree[len].h=tree[u].h+1;
            tree[u].right=len;
            buildtree(root-1,k+1,r,len);
        }
        return;
    }
    void bfs()
    {
        queue<int> s;
        s.push(1);
        while(!s.empty())
        {
            int k=s.front();
            if (tree[k].left!=-1) s.push(tree[k].left);
            if (tree[k].right!=-1) s.push(tree[k].right);
            if (n>1) printf("%d ",tree[k].num);
             else printf("%d\n",tree[k].num);
             n--;
             s.pop();
        }
        return;
    }
    int main()
    {
        scanf("%d",&n);
        for(i=1;i<=n;i++)
            scanf("%d",&a[i]);
        for(i=1;i<=n;i++)
            scanf("%d",&b[i]);
        for(i=1;i<=n;i++)
        {
            tree[i].num=0;
            tree[i].left=-1;
            tree[i].right=-1;
            tree[i].h=0;
        }
        len=1;
        tree[1].num=a[n];
        tree[1].h=1;
        buildtree(n,1,n,1);
        //for(i=1;i<=n;i++)
          //  printf("%d:%d %d\n",tree[i].num,tree[tree[i].left].num,tree[tree[i].right].num);
        bfs();
        return 0;
    }
  • 相关阅读:
    Redis(二)
    Redis(一)
    MyBatis--一级二级缓存
    MySQL优化
    HashMap
    ArrayList
    常用框架注解说明
    Linux常用基础命令
    SpringCloud--gateway路由配置
    JetBrains系列软件的插件安装
  • 原文地址:https://www.cnblogs.com/stepping/p/5674889.html
Copyright © 2011-2022 走看看