这题了解完全二叉树的数组存储方法就能写,也就是,若数组开始于 1,每个点 i 的左儿子的下标为 2*i,右儿子的下标为 2*i+1。根据这个递归即可,具体看注释。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e3+3;
int n;
int tree[maxn];
int heap;
vector<int> path;
void read() {
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> tree[i];
}
}
bool print(int i) {
if (i > n) return false; //越界了,说明该点为空
path.push_back(tree[i]);
bool flag1 = print(2*i+1); //先检查右子树
bool flag2 = print(2*i); //再检查左子树
if (!flag1 && !flag2) { //如果都为空,则打印路径
cout << tree[1];
for (int j = 1; j < path.size(); ++j) {
if (path[j] >= path[j-1]) { //如果路径是非增的
if (heap == 1 || heap == 0) {
heap = 1; //1代表最小堆
} else {
heap = -1; //-1代表不满足堆条件
}
} else if (path[j] <= path[j-1]) { //如果路径是非减的
if (heap == 2 || heap == 0) {
heap = 2; //2代表最大堆
} else {
heap = -1;
}
}
cout << " " << path[j];
}
cout << endl;
}
path.pop_back();
return true;
}
void solve() {
print(1);
if (heap == 1) {
cout << "Min Heap" << endl;
} else if (heap == 2) {
cout << "Max Heap" << endl;
} else if (heap == -1) {
cout << "Not Heap" << endl;
}
}
int main() {
read();
solve();
return 0;
}