• 数据结构


    L2-2. 树的遍历

    时间限制
    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

    直接看代码吧,利用递归构建二叉树,利用队列输出。

    #include <iostream>
    #include <string>
    #include <sstream>
    #include <queue>
    #define MAX 35
    
    using namespace std;
    
    int In[MAX],Out[MAX],ltr[MAX],rtr[MAX];
    int n;
    
    int build_tr(int l1,int r1,int l2,int r2)
    {
        if(l1 > r1) return 0;
    
        int root = Out[r2];
    
        int cur=l1;
        while(In[cur] != root)
            cur++;
        int cnt = cur-l1;
    
        ltr[root] = build_tr(l1,cur-1,l2,l2+cnt-1);     //???????????
        rtr[root] = build_tr(cur+1,r1,l2+cnt,r2-1);     //???????????
        return root;
    }
    
    void Out_put()
    {
        queue<int > a;
        int temp;
        int root=Out[n-1];
        int flag=0;
        a.push(root);
    
        while(!a.empty()){
            temp=a.front();
            if(!flag){
                cout<<temp;
                flag=1;
            }
            else
                cout<<" "<<temp;
    
            a.pop();
            if(ltr[temp])   a.push(ltr[temp]);
            if(rtr[temp])   a.push(rtr[temp]);
        }
        cout<<endl;
    }
    
    int main()
    {
        while(cin>>n)
        {
            for(int i = 0;i < n;i ++)   cin>>Out[i];
            for(int i = 0;i < n;i ++)   cin>>In[i];
    
            build_tr(0,n-1,0,n-1);
            Out_put();
        }
        return 0;
    }
    



  • 相关阅读:
    CMD命令提示符的基本操作指令
    JDBC连接Oracle
    JDBC连接MySQL
    Oracle树状结构的存储与展示
    C语言 深入学习
    C# widget
    C#深入多线程
    数据库常用知识
    ASP.NET开发总结
    ASP.NET —— Web Pages
  • 原文地址:https://www.cnblogs.com/Jstyle-continue/p/6351968.html
Copyright © 2020-2023  润新知