题意
给定二叉树的后序和中序遍历,要求输出特定的层次遍历,即间隔一层反转.
思路
主要是如何实现间隔一层反转.
方法一:
下一层的节点一定在遍历完上一层之后才遍历到, 可以根据这个特点进行处理: 设置一个buffer, 这个buffer仅仅存储该层的节点, 遍历到不属于该层的节点的时候处理该层: 如果层数为奇数就reverse, 然后输出 buffer的全部节点并清空buffer, 继续遍历.
方法二:
将节点分层存储起来, 统一处理.(方法二更好.)
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
方法一
#include "bits/stdc++.h"
using namespace std;
vector<int> in,pos;
struct Node{
int v;
Node *l{nullptr};
Node *r{nullptr};
};
Node* build(int posL, int posR, int inL, int inR){
if (posL > posR)
return nullptr;
Node* res = new Node{pos[posR]};
int i;
for(i=inL;i<=inR;i++) if (in[i] == res->v) break;
int numL = i - inL;
res->l = build(posL,posL+numL-1,inL,i-1);
res->r = build(posL+numL,posR-1,i+1,inR);
return res;
}
bool blank = false;
void printArray(vector<Node*>& a){
for(Node *p:a){
if (blank) printf(" %d",p->v);
else blank = true, printf("%d",p->v);
}
}
void show(Node *root){
queue<Node*> q; q.push(root);
vector<Node*> buffer;
map<Node*,int> layer; layer[root] = 1;
while (!q.empty()){
Node* p = q.front(); q.pop();
if (!buffer.empty() && layer[p] != layer[buffer.back()]){
if (layer[buffer.back()] % 2) reverse(buffer.begin(),buffer.end());
printArray(buffer);
buffer.clear();
}
buffer.push_back(p);
if (p->l != nullptr){
layer[p->l] = layer[p] + 1;
q.push(p->l);
}
if (p->r != nullptr) {
layer[p->r] = layer[p] + 1;
q.push(p->r);
}
}
if (!buffer.empty()){
if (layer[buffer.back()] % 2) reverse(buffer.begin(),buffer.end());
printArray(buffer);
}
}
int main(){
// freopen("input.txt","r",stdin);
int n; cin >> n; in.resize(n), pos.resize(n);
for(int i=0;i<n;i++) scanf("%d",&in[i]);
for(int i=0;i<n;i++) scanf("%d",&pos[i]);
Node* root = build(0,n-1,0,n-1);
show(root);
}
方法二:
#include "bits/stdc++.h"
using namespace std;
vector<int> in,pos;
struct Node{
int v;
Node *l{nullptr};
Node *r{nullptr};
};
Node* build(int posL, int posR, int inL, int inR){
if (posL > posR)
return nullptr;
Node* res = new Node{pos[posR]};
int i;
for(i=inL;i<=inR;i++) if (in[i] == res->v) break;
int numL = i - inL;
res->l = build(posL,posL+numL-1,inL,i-1);
res->r = build(posL+numL,posR-1,i+1,inR);
return res;
}
void show(Node *root){
queue<Node*> q; q.push(root);
map<int,vector<Node*>> res;
map<Node*,int> layer; layer[root] = 1;
while (!q.empty()){
Node* p = q.front(); q.pop();
res[layer[p]].push_back(p);
if (p->l != nullptr){
layer[p->l] = layer[p] + 1;
q.push(p->l);
}
if (p->r != nullptr) {
layer[p->r] = layer[p] + 1;
q.push(p->r);
}
}
bool blank = false;
for(auto &item:res){
vector<Node*>& a = item.second;
if (a.empty()) continue;
else if (layer[a.back()] % 2) reverse(a.begin(),a.end());
for(auto p:a){
if (blank) printf(" %d",p->v);
else blank = true, printf("%d",p->v);
}
}printf("\n");
}
int main(){
// freopen("input.txt","r",stdin);
int n; cin >> n; in.resize(n), pos.resize(n);
for(int i=0;i<n;i++) scanf("%d",&in[i]);
for(int i=0;i<n;i++) scanf("%d",&pos[i]);
Node* root = build(0,n-1,0,n-1);
show(root);
}