题意:输入一个树的层序遍历,判断是否是一个堆,输出堆的类型并输出后序遍历。
思路:递归判断子树是否是堆即可。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define lc(x) (x<<1)
#define rc(x) (x<<1|1)
const int MAX_N = 1100;
int M, N;
int tr[MAX_N];
int postorder[MAX_N], len;
void post(int p) {
if (p > N) return ;
post(lc(p));
post(rc(p));
postorder[len++] = tr[p];
}
int isHeap(int p) {
int p1 = -1, p2 = -1, pp = -1;
if ((lc(p)) <= N) {
p1 = isHeap(lc(p));
if (tr[p] > tr[lc(p)]) pp &= 1;
else if (tr[p] < tr[lc(p)]) pp &= 2;
}
if ((rc(p)) <= N) {
p2 = isHeap(rc(p));
if (tr[p] > tr[rc(p)]) pp &= 1;
else if (tr[p] < tr[rc(p)]) pp &= 2;
}
return (p1 & p2 & pp);
}
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
scanf("%d %d", &M, &N);
while (M--) {
for (int i = 1; i <= N; i++) scanf("%d", &tr[i]);
int flag = isHeap(1);
if (flag == 1) {
printf("Max Heap\n");
} else if (flag == 2) {
printf("Min Heap\n");
} else {
printf("Not Heap\n");
}
len = 0; post(1);
for (int i = 0; i < len; i++) {
if (i > 0) printf(" ");
printf("%d", postorder[i]);
}
printf("\n");
}
return 0;
}