题意
给出一颗完全二叉树的层次遍历,要求输出所有从根节点到叶子节点的所有路径(右子树优先),判断是否为最大堆或者最小堆。
思路
- 遍历的时候记录路径,遇到叶子节点就输出这条路径
- 遍历二叉树,同时进行判断是否为最大堆或者最小堆
#include "bits/stdc++.h"
using namespace std;
vector<int> temp;
int a[1010];
int n;
void show(){
bool blank = false;
for(int t:temp){
if (blank) printf(" ");
else blank = true;
printf("%d",a[t]);
}
printf("\n");
}
bool max_Heap = true;
bool min_Heap = true;
void dfs(int id){
if (id > n) return;
temp.push_back(id);
int l = 2*id; int r = l + 1;
if (l > n) show(); // is leaf node
else{ // non-leaf-node -> judge
int maxV = r <= n ? max(a[l],a[r]) : a[l];
int minV = r <= n ? min(a[l],a[r]) : a[l];
if (a[id] < maxV) max_Heap = false;
if (a[id] > minV) min_Heap = false;
}
dfs(r);
dfs(l);
temp.pop_back();
}
int main(){
// freopen("input.txt","r",stdin);
cin >> n;
for (int i = 1; i <= n; ++i) scanf("%d",&a[i]);
dfs(1);
if (max_Heap) printf("Max Heap\n");
else if (min_Heap) printf("Min Heap\n");
else printf("Not Heap\n");
}