zoukankan      html  css  js  c++  java
  • PAT(Advanced Level)A1127. ZigZagging on a Tree

    题意

    输出一个树的层序遍历,要求每一层都调转方向

    思路

    • 首先是根据中序序列和后序序列建树,这是常规操作
    • 用层序遍历,每次取出一层的结点,每到下一层都要调转方向一次

    代码

    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <unordered_map>
    #include <set>
    #include <string.h>
    #include <queue>
    using namespace std;
    vector<int> post, in, ans;
    int direction = 1;
    struct node {
        int val;
        struct node* left;
        struct node* right;
        node(int v): val(v), left(NULL), right(NULL){}
    };
    
    // 建树
    node* build_tree(int inL, int inR, int posL, int posR) {
        if(inL > inR)   return NULL;
        node* root = new node(post[posR]);
        int pos = inL;
        while(in[pos] != post[posR])    pos++;
        int num_left = pos - inL;
        root->left = build_tree(inL, pos - 1, posL, posL + num_left - 1);
        root->right = build_tree(pos + 1, inR, posL + num_left, posR - 1);
        return root;
    }
    // 层序遍历
    void bfs(node* root) {
        queue<node*> q;
        q.push(root);
        while(!q.empty()) {
            int len = q.size();
            vector<int> tmp;
            // 一次拿出一层的结点数
            for(int i = 0; i < len; i++) {
                auto it = q.front();
                q.pop();
                if(it->left)    q.push(it->left);
                if(it->right)   q.push(it->right);
                tmp.emplace_back(it->val);
            }
            // 调转方向
            if(direction != 0) {
                direction = 0;
                reverse(tmp.begin(), tmp.end());
            }else
                direction = 1;
            for(auto it: tmp)   ans.emplace_back(it);
        }
    }
    int main() {
        int N;
        cin >> N;
        post.resize(N); in.resize(N);
        for(int i = 0; i < N; i++)  cin >> in[i];
        for(int i = 0; i < N; i++)  cin >> post[i];
        node* root = build_tree(0, N - 1, 0, N - 1);
        bfs(root);
        cout << ans.front();
        for(int i = 1; i < N; i++)  cout << " " << ans[i];
        return 0;
    }
    
    如有转载,请注明出处QAQ
  • 相关阅读:
    OO第四次暨期末总结
    OO第九到十一次作业小结
    OO第五到七次作业小结
    OO前三次作业阶段小结
    数据预处理相关
    Latex+VScode安装
    python学习网站+查询网站
    arcgis画图中添加带箭头的直线
    在ArcGIS 中标注中竖排文字
    vs2015使用fopen时遇到unsafe问题
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/14528364.html
Copyright © 2011-2022 走看看