zoukankan      html  css  js  c++  java
  • pat甲级 1020 Tree Traversals

    题意:给出一颗二叉树的后序遍历序列和中序遍历序列,求这棵二叉树的层序遍历序列。

    思路:给出的数的长度为N,后序遍历的最后一个是树的根节点,在中序遍历中找到这个点就可以将      一棵树分为左子树部分和右子树部分,递归下去就可以得到要求的二叉树,再利用BFS算法求   得层序遍历的输出结果。

    注意点:输出时需要注意控制最后一个数后面的空格不应当被输出

    AC代码:

    #include<cstdio>
    #include<cstring>
    #include<queue>
    #include<algorithm>
    using namespace std;
    const int maxn=50;
    struct node{
        int data;
        node* lchild;
        node* rchild;
    }; 
    int pre[maxn],in[maxn],post[maxn];
    int n;
    node* creat(int postL,int postR,int inL,int inR){
        if(postL>postR){
            return NULL;
        }
        node* root=new node;
        root->data=post[postR];
        int k;
        for(k=inL;k<=inR;k++){
            if(in[k]==post[postR]){
                break;
            }
        }
        int numLeft=k-inL;
        root->lchild=creat(postL,postL+numLeft-1,inL,k-1);
        root->rchild=creat(postL+numLeft,postR-1,k+1,inR);
        return root; 
    }
    
    int num=0;
    void BFS(node* root){
        queue<node*>q;
        q.push(root);
        while(!q.empty()){
            node* now=q.front();
            q.pop();
            printf("%d",now->data);
            num++;
            if(num<n)printf(" ");
            if(now->lchild!=NULL) q.push(now->lchild);
            if(now->rchild!=NULL) q.push(now->rchild);
        } 
    }
    
    int main(){
        scanf("%d",&n);
        for(int i=0;i<n;i++){
            scanf("%d",&post[i]);
        }
        for(int i=0;i<n;i++){
            scanf("%d",&in[i]);
        }
        node* root=creat(0,n-1,0,n-1);
        BFS(root);
    }

                

  • 相关阅读:
    Delphi stdCall意义
    Delphi 与 DirectX 之 DelphiX(10): TPictureCollectionItem.StretchDraw
    delphi中的TCollection
    Delphi XE5教程8:使用Delphi命名空间
    在 centos 系统中添加审计用户并利用 sudoers 进行权限控制
    在 centos 8 中添加 sudoer 用户
    React.Fragment
    js保留两位小数方法总结
    正则表达式的() [] {} 的区别
    Typora如何配置gitee图床
  • 原文地址:https://www.cnblogs.com/fromzore/p/10028836.html
Copyright © 2011-2022 走看看