PAT A1127 ZigZagging on a Tree
Sample Input:
8
12 11 20 17 1 15 8 5
12 20 17 11 15 8 5 1
Sample Output:
1 11 5 8 17 12 20 15
- 思路 1:
- 先根据后序中序建树
- 对树层序遍历,将每层节点依次加入vector[layer]
- 对vector,按层输出:奇数层正序输出, 偶数层逆序输出
- code 1:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 30;
struct node{
int data, layer;
node *lc, *rc;
node(){lc = rc = NULL; layer = 0;}
};
vector<int> posto, ino;
node* create(int postL, int postR, int inL, int inR){
//建树
if(inL > inR){
return NULL;
}
node* r = new node;
r->data = posto[postR];
int idex = inL;
while(idex <= inR && ino[idex] != posto[postR]) idex++;
int numL = idex - inL;
r->lc = create(postL, postL+numL-1, inL, idex-1);
r->rc = create(postL+idex-inL, postR-1, idex+1, inR);
return r;
}
vector<int> ans[maxn];
void levelOrder(node* r){
queue<node*> q;
q.push(r);
while(!q.empty()){
node* now = q.front();
q.pop();
ans[now->layer].push_back(now->data); //记录每层节点
if(now->lc != NULL){
now->lc->layer = now->layer+1;
q.push(now->lc);
}
if(now->rc != NULL){
now->rc->layer = now->layer+1;
q.push(now->rc);
}
}
}
int main(){
int n;
scanf("%d", &n);
posto.resize(n); ino.resize(n);
for(int i = 0; i < n; ++i){
scanf("%d", &ino[i]);
}
for(int i = 0; i < n; ++i){
scanf("%d", &posto[i]);
}
node* root = create(0, n-1, 0, n-1);
levelOrder(root);
printf("%d", ans[0][0]);
for(int i = 1; i < maxn && ans[i].size() != 0; ++i){
if(i % 2 != 0){
for(int j = 0; j < ans[i].size(); ++j)
printf(" %d", ans[i][j]);
}else{
for(int j = ans[i].size()-1; j >= 0; --j)
printf(" %d", ans[i][j]);
}
}
// cout << root->lc->data << " " << root->rc->data;
return 0;
}
- 思路 2:不建树:直接通过Create(),先序遍历,引入参数dep,将每一层加入一个二维数组
因为从整体上看,先序遍历,"每层"都最先遍历到靠左边的节点,按层push进对应层的数组(depth[dep])即可得到每层都是从左到右的二维数组
这里为了遍历输出的方便,使用了双端队列,奇数层push_back()尾插
,偶数层push_front()头插
,这样按顺序输出即是zigzag
- T2 code:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 50;
int in[maxn], post[maxn];
deque<int> depth[maxn];
int Max = 0;
void Create(int postL, int postR, int inL, int inR, int dep){
if(postL > postR) return;
Max = max(Max, dep);
int id = inL, root = post[postR];
while(id < inR && in[id] != root) id++;
int numL = id - inL;
if(dep % 2 == 1) depth[dep].push_back(root);
else depth[dep].push_front(root);
Create(postL, postL + numL - 1, inL, id - 1, dep + 1); //左
Create(postL + numL, postR - 1, id + 1, inR, dep + 1); //右
}
int main(){
int n;
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]);
}
Create(0, n - 1, 0, n - 1, 0);
int cnt = 0;
for(int i = 0; i <= Max; ++i){
for(int j = 0; j < depth[i].size(); ++j){
printf("%d", depth[i][j]);
if(++cnt < n) printf(" ");
}
}
return 0;
}