• L2-006 树的遍历 (25 分)


    L2-006 树的遍历 (25 分)

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

    输入格式:

    输入第一行给出一个正整数 (N ; (leq 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<bits/stdc++.h>
    using namespace std;
    int n,a[35],b[35],tot;
    struct node
    {
        int val;
        node*lson,*rson;
    };
    typedef node* Tree;
    inline Tree solve(int x,int y,int l,int r)
    {
        Tree root=new(node);
        root->val=b[r];
        root->lson=root->rson=NULL;
        if(x==y)return root;
        for(int i=x;i<=y;i++)
        {
            if(a[i]==b[r])
            {
                if(1<=i-x)root->lson=solve(x,i-1,l,l+i-x-1);
                if(l+i-x+1<=r)root->rson=solve(i+1,y,l+i-x,r-1);
            }
        }
        return root;
    }
    inline void print(Tree root)
    {
        queue<Tree>q;
        q.push(root);
        while(!q.empty())
        {
            Tree now=q.front();
            q.pop();
            cout<<now->val;
            tot++;
            if(tot<n)cout<<' ';
            else cout<<endl;
            if(now->lson!=NULL)q.push(now->lson);
            if(now->rson!=NULL)q.push(now->rson);
        }
    }
    Tree root=NULL;
    int main()
    {
        cin>>n;
        for(int i=1;i<=n;i++)cin>>b[i];
        for(int i=1;i<=n;i++)cin>>a[i];
        root=solve(1,n,1,n);
        print(root);
        return 0;
    }
    
  • 相关阅读:
    【Eclipse】怎样把代码复制到word中并保持颜色
    windows下配置gvim
    这是给开发者的弥天大谎还是至理名言?
    Linux中常用软件安装(基于Ubuntu)
    MyEclipse 9.1优化技巧
    【数据库复习】函数依赖
    Windows下使用Flex入门
    【数据库复习】SQL
    浏览器中的“Linux”
    Unity开发原则
  • 原文地址:https://www.cnblogs.com/LengYun/p/14691105.html
Copyright © 2020-2023  润新知