zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    python学习笔记(五)
    python学习笔记(七)
    python小游戏——猜数字2.0
    python学习笔记(六)
    python小游戏——猜数字2.0
    python学习笔记(五)
    python中的in运算符
    python学习笔记(七)
    jmeter(4)响应断言 json断言 beanshell断言
    jmeter(2)几种不同的contenttype方式
  • 原文地址:https://www.cnblogs.com/LengYun/p/14691105.html
Copyright © 2011-2022 走看看