#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;
}
PAT (Advanced Level) Practice A1127 ZigZagging on a Tree (30 分) (中后序建树、层次遍历、栈)
最新推荐文章于 2020-02-13 10:37:04 发布