PAT (Advanced Level) Practice A1127 ZigZagging on a Tree (30 分) (中后序建树、层次遍历、栈)

原题链接

#include <algorithm>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
using namespace std;

const int MAX = 50, INF = 1<<30;

typedef struct BiTNode
{
    int data, level;
    struct BiTNode *lChild, *rChild;
}BiTNode, *BiTree;


int Pre[MAX], Post[MAX], In[MAX];
int N, cnt = 0;

BiTree creatTree(int inL, int inR, int postL, int postR)//根据中后序建树
{
    if(inL > inR || postL > postR) return NULL;
    BiTree T = new BiTNode;
    T->data = Post[postR];
    int k = inL;
    while(k <= inR && In[k] != Post[postR]) k++;
    if(k > inR) return NULL;
    T->lChild = creatTree(inL, k-1, postL, postL+k-inL-1);
    T->rChild = creatTree(k+1, inR, postL+k-inL, postR-1);
    return T;
}

vector<BiTree> V;
void BFS(BiTree T)//正常的层次遍历,按顺序存放至V中
{
    queue<BiTree> Q;
    Q.push(T);
    T->level = 1;
    while(!Q.empty())
    {
        T = Q.front();
        Q.pop();
        V.push_back(T);
        if(T->lChild)
        {
            T->lChild->level = T->level + 1;
            Q.push(T->lChild);
        }
        if(T->rChild)
        {
            T->rChild->level = T->level + 1;
            Q.push(T->rChild);
        }
    }
}

int main()
{
    scanf("%d", &N);
    for(int i=0; i<N; i++) scanf("%d", &In[i]);
    for(int i=0; i<N; i++) scanf("%d", &Post[i]);
    BiTree ROOT = creatTree(0, N-1, 0, N-1);
    BFS(ROOT);
    printf("%d", V[0]->data);
    for(int i=1; i<V.size(); )
    {
        if(V[i]->level%2 == 0) printf(" %d", V[i++]->data);//偶数层次直接打印
        else//奇数层次反序打印,这里用了栈进行逆序
        {
            stack<int> S;
            while(i<V.size() && V[i]->level%2) S.push(V[i++]->data);
            while(!S.empty()) printf(" %d", S.top()), S.pop();
        }
    }
    printf("\n");
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值