2020年团体程序设计天梯赛 L2-3 完全二叉树的层序遍历
思路:
水题,略过
Tip:
满二叉树和完全二叉树的性质
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1000 + 5;
struct point {
int num;
point *left;
point *right;
};
int ceng[maxn];
int a[maxn];
int nowP = 1;
int n;
point *dfs(point *now, int nowCeng) {
if (!ceng[nowCeng])
return NULL;
ceng[nowCeng]--;
now = (point *) malloc(sizeof(point));
now->left = NULL;
now->right = NULL;
now->left = dfs(now->left, nowCeng + 1);
now->right = dfs(now->right, nowCeng + 1);
now->num = a[nowP++];
return now;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
int i, j = 1, ans = 0;
for (i = 1;; i *= 2, j++) {
if (ans + i > n) {
ceng[j] = n - ans;
break;
}
ceng[j] = i;
ans += i;
}
point *head;
head = dfs(head, 1);
queue<point *> que;
que.push(head);
vector<int> v;
while (!que.empty()) {
point *now = que.front();
que.pop();
v.push_back(now->num);
if (now->left != NULL)
que.push(now->left);
if (now->right != NULL)
que.push(now->right);
}
bool first = true;
for (auto k:v) {
if (first) {
first = false;
cout << k;
} else
cout << " " << k;
}
return 0;
}

浙公网安备 33010602011771号