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;
    }
     
  • 相关阅读:
    【MongoDB初识】-结合C#简单使用,驱动2.x
    【NuGet】打包上传一条龙服务
    【NuGet】搭建自己团队或公司的NuGet
    【MongoDB初识】-其他操作
    【MongoDB初识】-条件操作符
    【MongoDB初识】-增删改
    【MongoDB初识】-安装篇
    【面试题】-100盏灯
    【微信开发】一获取用户授权(静默授权方式)
    XML序列化及反序列化
  • 原文地址:https://www.cnblogs.com/bianjunting/p/12555671.html
Copyright © 2011-2022 走看看