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;
}