各种二叉堆的操作。。。(应该还有一种堆叫“斐波那契堆”)
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int m, n;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(0), left(nullptr), right(nullptr) {};
TreeNode(int _val) : val(_val), left(nullptr), right(nullptr) {};
TreeNode(int _val, TreeNode* _left, TreeNode* _right) : val(_val), left(_left), right(_right) {};
~TreeNode() {};
};
TreeNode* buildTree(vector<int>& vals) {
// corner case
if (vals.empty()) return nullptr;
auto root = new TreeNode(vals.front());
queue<pair<TreeNode*, int>> q;
q.emplace(root, 0);
while (not q.empty()) {
const auto [cur, idx] = q.front(); q.pop();
const int l_idx = idx << 1 | 1;
if (l_idx >= n) break;
cur->left = new TreeNode(vals[l_idx]);
q.emplace(cur->left, l_idx);
const int r_idx = (idx << 1) + 2;
if (r_idx >= n) break;
cur->right = new TreeNode(vals[r_idx]);
q.emplace(cur->right, r_idx);
}
return root;
}
vector<vector<int>> allPathsToLeafNode(TreeNode* root) {
vector<vector<int>> ans;
vector<int> cur;
function<void(TreeNode*)> dfs = [&](TreeNode* r) {
if (!r) return;
cur.emplace_back(r->val);
if (r->left == r->right) { // leaf node
ans.emplace_back(cur);
return;
}
for (const auto& child : {r->left, r->right}) {
if (!child) continue;
dfs(child);
cur.pop_back(); // backtracking ...
}
};
dfs(root);
return ans;
}
bool is_maximum_heap(vector<vector<int>>& allPaths) {
for (const auto& p : allPaths)
if (!is_sorted(rbegin(p), rend(p))) return false;
return true;
}
bool is_minimum_heap(vector<vector<int>>& allPaths) {
for (const auto& p : allPaths)
if (!is_sorted(begin(p), end(p))) return false;
return true;
}
void postOrder(TreeNode* root, vector<int>& ans) {
if (!root) return;
postOrder(root->left, ans);
postOrder(root->right, ans);
ans.emplace_back(root->val);
}
void printAns(vector<int>& ans) {
for (int i = 0; i < ans.size(); ++i) {
printf("%d", ans[i]);
if (i < ans.size() - 1) printf(" ");
}
printf("\n");
}
int main(void) {
scanf("%d %d", &m, &n);
while (m--) {
vector<int> vals(n);
for (int i = 0; i < n; ++i) cin >> vals[i];
auto root = buildTree(vals);
auto allPaths = allPathsToLeafNode(root);
if (is_maximum_heap(allPaths)) puts("Max Heap");
else if (is_minimum_heap(allPaths)) puts("Min Heap");
else puts("Not Heap");
vector<int> ans;
postOrder(root, ans);
printAns(ans);
}
}