zoukankan      html  css  js  c++  java
  • PAT.Tree traversals(树的重构 + 层序输出)

    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 (≤), 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 <iostream>
    #include <algorithm>
    #include <queue>
    using namespace std;
    
    struct _root {
        int data;
        _root *left, *right;
    };
    int n;
    const int maxn = 30 + 5;
    
    int post[maxn], inord[maxn];
    
    _root *head = new _root;
    
    _root* build(int pl, int pr, int il, int ir) {
        _root* root = new _root;
        root -> data = post[pr];
        if(root -> data == post[n - 1]) head = root;
        root -> left = root -> right = NULL;
        int temp = find(inord + il, inord + ir + 1, post[pr]) - inord - il;
        if(temp > 0)
            root -> left = build(pl, pl + temp - 1, il, il + temp - 1);
        if(pl + temp <= pr - 1)
            root -> right = build(pl + temp, pr - 1, il + temp + 1, ir);
        return root;
    }
    
    queue <_root*> que;
    queue <int> ans;
    
    void print(_root *root) {
        if(root == NULL) return;
        que.push(root);
        while(!que.empty()) {
            _root * now = que.front();
            que.pop();
            ans.push(now -> data);
            if(now -> left) que.push(now -> left);
            if(now -> right) que.push(now -> right);
        }
    }
    
    int main() {
        cin >> n;
        for(int i = 0; i < n; i ++) cin >> post[i];
        for(int i = 0; i < n; i ++) cin >> inord[i];
        build(0, n - 1, 0, n - 1);
        print(head);
        cout << ans.front();
        ans.pop();
        while(!ans.empty()) {
            cout << ' ' << ans.front();
            ans.pop();
        }
        cout << endl;
        return 0;
    }
     
  • 相关阅读:
    Mysql 从入门到遗忘
    Centos7开放及查看端口
    创建及修改数据库
    02_python是一种什么语言?
    03_SQL server数据类型
    02_关系数据库
    01_初识数据库
    kali 更新源
    01_Python简介
    Alertmanager高可用
  • 原文地址:https://www.cnblogs.com/bianjunting/p/12555671.html
Copyright © 2011-2022 走看看