判断和后序遍历分别写成了两个单独函数。
按照堆的定义做即可。
#include<iostream>
#include<vector>
using namespace std;
vector<int> heap,post;
int M,N;
bool Max,Min;
void panduan(int index){
if(index>N) return;
if((2*index<=N&&heap[2*index]>heap[index])||(2*index+1<=N&&heap[2*index+1]>heap[index])){
Max=false;
}
if((2*index<=N&&heap[2*index]<heap[index])||(2*index+1<=N&&heap[2*index+1]<heap[index])){
Min=false;
}
panduan(2*index);
panduan(2*index+1);
}
void Post(int index){
if(index>N) return;
Post(2*index);
Post(2*index+1);
post.push_back(heap[index]);
}
int main(){
cin>>M>>N;
for(int i=0;i<M;i++){
heap.clear();
post.clear();
heap.resize(N+1);
for(int j=1;j<=N;j++){
scanf("%d",&heap[j]);
}
Max=true;Min=true;
panduan(1);
if(Max){
printf("Max Heap\n");
}else if(Min){
printf("Min Heap\n");
}else{
printf("Not Heap\n");
}
Post(1);
for(int j=0;j<N;j++){
if(j==0){
printf("%d",post[j]);
}else{
printf(" %d",post[j]);
}
}
cout<<endl;
}
return 0;
}
|