• 1020. Tree Traversals (25)


    Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.

    Input Specification:

    Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.

    Output Specification:

    For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.

    Sample Input:

    7
    2 3 1 5 7 6 4
    1 2 3 4 5 6 7
    

    Sample Output:

    4 1 6 3 5 7 2
    #include<cstdio>
    #include<queue>
    using namespace std;
    struct Node{
        int data;
        Node* lchild;
        Node* rchild;
    }node;
    
    int in[35],post[35],level[35];
    int n;
    
    Node* create(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 = create(postL,postL+numLeft-1,inL,k-1); //左子树个数 
        root->rchild = create(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); //now节点后继 
            if(now->rchild != NULL) q.push(now->rchild); //2018.8.8 错误1
        }
    }
    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 = create(0,n-1,0,n-1); 
        BFS(root);
        return 0;
    }
  • 相关阅读:
    登录注册测试用例
    礼盒抽奖测试点
    jmeter性能测试
    selenium的常用API及案例演示
    jmeter+ant+jenkins接口自动化测试框架
    开源性能测试工具jmeter
    Jmeter响应断言,性能测试,定时器,cookie
    Charles的介绍,配置与使用
    异常捕获以及文件的相关操作
    函数封装及面向对象
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/8565193.html
Copyright © 2020-2023  润新知