- 用数组记录二叉树
- 用一个深度优先遍历输出
- 用两个迭代分别检查是否为最大堆或最小堆
#include <iostream>
#include<cstdio>
#include<vector>
using namespace std;
vector<int> outputdata;
void output() {
int i;
for (i = 0; i < outputdata.size() - 1; i++) {
printf("%d ", outputdata[i]);
}
printf("%d\n", outputdata[i]);
}
void DFS(int num[], int N, int now) {
outputdata.push_back(num[now]);
if (now * 2 + 1 >= N) {
output();
}
else {
if (now * 2 + 2 < N) {
DFS(num, N, now * 2 + 2);
}
if (now * 2 + 1 < N) {
DFS(num, N, now * 2 + 1);
}
}
outputdata.pop_back();
}
bool maxheap(int num[], int N, int now) {
int left = now * 2 + 1;
int right = now * 2 + 2;
if (right < N) {
return maxheap(num, N, right) && maxheap(num, N, left) && (num[now] >= num[right]) && (num[now] >= num[left]);
}
else if (left < N) {
return maxheap(num, N, left) && (num[now] >= num[left]);
}
return true;
}
bool minheap(int num[], int N, int now) {
int left = now * 2 + 1;
int right = now * 2 + 2;
if (right < N) {
return minheap(num, N, right) && minheap(num, N, left) && (num[now] <= num[right]) && (num[now] <= num[left]);
}
else if (left < N) {
return minheap(num, N, left) && (num[now] <= num[left]);
}
return true;
}
int main()
{
int N;
scanf("%d", &N);
int num[1010];
for (int i = 0; i < N; i++) {
scanf("%d", &num[i]);
}
DFS(num, N, 0);
bool maxh = maxheap(num, N, 0);
bool minh = minheap(num, N, 0);
if (maxh) {
printf("Max Heap\n");
}
else if (minh) {
printf("Min Heap\n");
}
else printf("Not Heap\n");
return 0;
}