PAT【甲级】1127

题目链接:PAT【甲级】1127
题目简述:这个题目是给定一棵树的中序和后序序列,要求输出这棵树的层次遍历序列【但要求是“之”字型的层次遍历】

#include<bits/stdc++.h>
using namespace std;

vector<int> pre(30), in(30), indexu, temp, ans;//indexu用来记录每个节点所在的层次,temp存储bfs时每层的节点序列,ans答案输出序列
unordered_map<int, int> indice;//indice记录后序序列中的每个点在中序中的位置,
struct node{
    int value;
    struct node *lChild, *rChild;
    node(int v):value(v){}
};

node* buildTree(int pivot, int inl, int inr){
    if(inl > inr)
        return NULL;
    node *root = new node(pre[pivot]);
    int pos = indice[pre[pivot]];
    root->lChild = buildTree(pivot - (inr - pos) - 1, inl, pos - 1);
    root->rChild = buildTree(pivot - 1, pos + 1, inr);
    return root;
}

int main(){
    int n;
    cin >> n;
    for (int i = 0; i < n;i++){
        cin >> in[i];
        indice[in[i]] = i;
    } 
    for (int i = 0; i < n;i++)
        cin >> pre[i];
    node *root = buildTree(n - 1, 0, n - 1);
    queue<node *> q;
    q.emplace(root);
    indexu.push_back(0);
    int count = 0;//count变量和indexu是同步的,indexu[count]表示count号节点所在的层次
    while(!q.empty()){
        node* p = q.front();
        temp.push_back(p->value);
        q.pop();
        count++;
        if(q.empty() || indexu[count - 1] != indexu[count]){
            if(indexu[count - 1] % 2 == 0){
                for (int i = temp.size() - 1; i >= 0;i--)
                    ans.push_back(temp[i]);
            }else{
                for (int i = 0; i < temp.size();i++)
                    ans.push_back(temp[i]);
            }
            temp.clear();
        }
        if(p->lChild != NULL){
            q.emplace(p->lChild);
            indexu.push_back(indexu[count - 1] + 1);
        }
        if(p->rChild != NULL){
            q.emplace(p->rChild);
            indexu.push_back(indexu[count - 1] + 1);
        }
    }
    cout << ans[0];
    for (int i = 1; i < ans.size();i++)
        cout << " " << ans[i];
    return 0;
}

读完题目,直观想法就是去构建这棵树然后进行层次遍历。但是如何输出之字型呢?那就需要去维护一个变量来记录这是第几层,这样就可以逆序、顺序输出了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值