zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    3.1 虚拟机执行子系统--类文件结构
    13.分解让复杂问题简单(3)
    中文文本中的关键字提取
    中文分词工具 jieba 和 HanLP
    中文NLP的完整机器处理流程
    IDEA导入Eclipse的Web项目
    【ML-15】主成分分析(PCA)
    【ML-13-4】隐马尔科夫模型HMM--预测问题Viterbi(维特比)算法
    【ML-13-3】隐马尔科夫模型HMM--Baum-Welch(鲍姆-韦尔奇)
    【ML-13-2】隐马尔科夫模型HMM--前向后向算法
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/8565193.html
Copyright © 2011-2022 走看看