题意:
给一个二叉树的层次遍历,问是什么类型的堆,是大顶堆还是小顶堆,然后输出这个树的后续遍历
题解:
大小堆根直接比较a[i]与a[i/2]即可
因为给的树的层次遍历,i就是i/2儿子
后序遍历,对于节点index分别遍历孩子index2和右孩子index2+1,遍历完左右子树输出根节点
代码建议背诵
代码:
#include <iostream>
using namespace std;
int a[1005], m, n;
void postOrder(int index) {
if (index > n) return;
postOrder(index * 2);
postOrder(index * 2 + 1);
printf("%d%s", a[index], index == 1 ? "\n" : " ");
}
int main() {
scanf("%d %d", &m, &n);
while (m--) {
int minn = 1, maxn = 1;
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
for (int i = 2; i <= n; i++) {
if (a[i] > a[i / 2]) maxn = 0;
if (a[i] < a[i / 2]) minn = 0;
}
if (maxn == 1) printf("Max Heap\n");
else if (minn == 1) printf("Min Heap\n");
else printf("Not Heap\n");
postOrder(1);
}
return 0;
}