1127 ZigZagging on a Tree (30 分)
作者:互联网
蛇形输出层序遍历,这个只要记录每一层的遍历序列,然后输出之前该翻转的翻转一下就可以了,然后看了看自己一年之前提交的,思路真的是一模一样,就是代码风格变了,
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;
struct node {
int val, lchild, rchild, level;
} tree[35];
int tot, maxlevel;
int post[35], in[35];
vi v[35];
map<int, int> mp;
int create(int postl, int postr, int inl, int inr) {
if (postl > postr) return -1;
int root = tot++; tree[root].val = post[postr];
int k = mp[post[postr]];
tree[root].lchild = create(postl, postl + k - inl - 1, inl, k - 1);
tree[root].rchild = create(postl + k - inl, postr - 1, k + 1, inr);
return root;
}
void layerorder(int root) {
queue<int> q;
q.push(root);
tree[root].level = 0;
while (!q.empty()) {
int now = q.front(); q.pop();
int l = tree[now].lchild, r = tree[now].rchild;
int level = tree[now].level;
v[level].pb(tree[now].val);
if (level > maxlevel) maxlevel = level;
if (l != -1) { q.push(l); tree[l].level = level + 1; }
if (r != -1) { q.push(r); tree[r].level = level + 1; }
}
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) { cin >> in[i]; mp[in[i]] = i; }
for (int i = 0; i < n; i++) cin >> post[i];
int root = create(0, n - 1, 0, n - 1);
layerorder(0); int ok = 0;
for (int i = 0; i <= maxlevel; i++) {
if (i && i % 2 == 0) reverse(all(v[i]));
for (int j = 0; j < v[i].size(); j++) cout << (ok++ ? " " : "") << v[i][j];
}
return 0;
}
标签:now,level,int,tree,30,Tree,postl,ZigZagging,root 来源: https://blog.csdn.net/weixin_46709784/article/details/118634368