【Python】PAT 甲级 A1147:Heaps(大小堆)
题目内容
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:
Sample Output:
题目要点
本题 30 分,考察的是堆的判定,并输出堆的后序遍历序列。
处理堆的问题时,首先要利用堆本身是完全二叉树的性质迅速定位左右孩子节点。根节点要从下标1开始存储,对于任意节点root来说,其左孩子下标为2*root,右孩子下标为2*root+1,父亲下标为root//2(向下取整)。有了这些结论就可以通过遍历各个节点判断是否符合堆的性质。
如果完全二叉树的所有孩子节点都比其父亲节点小,那么这就是一个最大堆;反之,所有孩子节点都比父亲节点大是最小堆。如果既不是最小堆、又不是最大堆,那么该完全二叉树就不是堆。
源代码