In computer science, a heap is a specialized tree-based data structure that satisfies the heap property: if P is a parent node of C, then the key (the value) of P is either greater than or equal to (in a max heap) or less than or equal to (in a min heap) the key of C. A common implementation of a heap is the binary heap, in which the tree is a complete binary tree. (Quoted from Wikipedia at https://en.wikipedia.org/wiki/Heap_(data_structure))
Your job is to tell if a given complete binary tree is a heap.
Input Specification:
Each input file contains one test case. For each case, the first line gives two positive integers: M (≤ 100), the number of trees to be tested; and N (1 < N ≤ 1,000), the number of keys in each tree, respectively. Then M lines follow, each contains N distinct integer keys (all in the range of int), which gives the level order traversal sequence of a complete binary tree.
Output Specification:
For each given tree, print in a line Max Heap
if it is a max heap, or Min Heap
for a min heap, or Not Heap
if it is not a heap at all. Then in the next line print the tree's postorder traversal sequence. All the numbers are separated by a space, and there must no extra space at the beginning or the end of the line.
Sample Input:
3 8
98 72 86 60 65 12 23 50
8 38 25 58 52 82 70 60
10 28 15 12 34 9 8 56
Sample Output:
Max Heap
50 60 65 72 12 23 86 98
Min Heap
60 58 52 38 82 70 25 8
Not Heap
56 12 34 28 9 8 15 10
阅读题意,发现这题有两个要求,其一是判断给出的数据结构是否构成一个堆,其二是将这个堆形成的二叉树通过后序遍历输出。需要解决的问题:1.用什么数据结构去模拟 2.如何去进行判断和输出
对于1,观察到可以通过建立一个数组来进行模拟,假设某个点的下标为 i ,访问其左孩子的下标便为 2 * i , 右孩子的下标为 2 * i + 1.之前做过了甲级 1155,其中就将堆用数组模拟,通过 i = 2 下标开始一直for循环到 n,进而与 i / 2 进行比较从而判断这个堆是大顶堆或者小顶堆。 当 a[ i ]> a [ i / 2 ]时,is_max=0 ,证明不是大顶堆,当a [ i ] <a [ i / 2 ]时,is_min=0, 证明不是小顶堆。在for循环完成后,通过is_max,is_min 的值对大小顶堆进行判断(https://blog.csdn.net/qq_38846633/article/details/96505255)。判断完成大小顶堆后,下一步需要将二叉树进行后序遍历输出,这一块暂时背下后序遍历的公式,不需要进行类dfs深度搜索的思考(一直没想出来用类dfs写出后序遍历)。至于最后的输出,控制下标为1时输出数字换行,不为1时输出数字加空格。一开始写的下标为n时输出单个数字,而不为n时输出空格加数字,在最后添上空格而会报错。也没有弄清是什么原因,希望之后多积累些关于输出过程中空格和换行的技巧
完整代码如下:
#include <bits/stdc++.h>
using namespace std;
int a[1000];
int m,n;
void pos_order(int i)
{
int l=2*i;
int r=2*i+1;
if(i>=n+1)
{
return;
}
pos_order(l);
pos_order(r);
if(i==1)
{
cout<<a[i]<<endl;
}
else
{
cout<<a[i]<<" ";
}
}
int main()
{
cin>>m>>n;
while(m--)
{
int is_max=1;
int is_min=1;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
for(int i=2;i<=n;i++)
{
if(a[i]<a[i/2])
{
is_min=0;
}
else if(a[i]>a[i/2])
{
is_max=0;
}
}
if(is_max==0)
{
if(is_min==1)
{
cout<<"Min Heap"<<endl;
}
else if(is_min==0)
{
cout<<"Not Heap"<<endl;
}
}
else if(is_max==1&&is_min==0)
{
cout<<"Max Heap"<<endl;
}
pos_order(1);
}
return 0;
}