第十五天PAT-A1127 ZigZagging on a Tree中序后序建树Z形层次遍历

A1127

Description:

给出一棵树的中序、后序遍历序列,求该树的Z形层次遍历序列;

思路:

  • 正常建树,在建树过程中记录下每层的节点数目,然后广搜求出层次遍历结果,并针对每层的节点进行反转;
  • 写代码要注意细节,64行i范围少了个等号,结果将导致最多一行序列没有反转;
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 35;
struct node{
    int v;
    node *lchild, *rchild;
};
int level[10], maxlevel = -1;
node* create(int v){
    node *Node = new node;
    Node->v = v;
    Node->lchild = Node->rchild = NULL;
    return Node;
}
int n, in[maxn], post[maxn];
node* con(int inL, int inR, int postL, int postR, int l){
    if(inL > inR) return NULL;
    node *root = new node;
    root->v = post[postR];
    if(l > maxlevel) maxlevel = l;
    level[l]++;
    int i;
    for(i = 1; i <= n; i++) if(in[i]==post[postR]) break;
    int leftnum = i - inL;
    root->lchild = con(inL, i-1, postL, postL+leftnum-1, l+1);
    root->rchild = con(i+1, inR, postL+leftnum, postR-1, l+1);
    return root;
}
vector<int>ans;
void bfs(node* tree){
    queue<node*>q;
    q.push(tree);
    while(!q.empty()){
        node* now = q.front();
        q.pop();
        ans.push_back(now->v);
        if(now->lchild != NULL) q.push(now->lchild);
        if(now->rchild != NULL) q.push(now->rchild);
    }
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
    scanf("%d", &n);
    for(int i = 1; i <= n; i++)
        scanf("%d", &in[i]);
    for(int i = 1; i <= n; i++)
        scanf("%d", &post[i]);
    node* tree;
    tree = con(1, n, 1, n, 0);
    bfs(tree);
    int base = 0;
    for(int i = 0; i <= maxlevel; i++){
        if(i%2 == 0)
            reverse(ans.begin()+base, ans.begin()+base+level[i]);
        base+=level[i];
    }
    for(int i = 0; i < ans.size(); i++){
        if(i) printf(" ");
        printf("%d", ans[i]);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值