大小根堆判断+后序遍历
1. 原文
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:
1 | 3 8 |
Sample output:
1 | Max Heap |
2. 解析
堆判断:
大根堆 :根>左结点 && 根>左结点 ;level[0]>level[1] 预测为大根堆 flag=1
小根堆 :根<左结点 && 根<左结点 ;level[0]<level[1] 预测为小根堆 flag=-1
再根据flag判断:
- flag=1 判断 level[i]<level[2i+1] || level[i]<level[2i+2] 存在则不是大根堆
- flag=-1 判断 level[i]>level[2i+1] || level[i]>level[2i+2] 存在则不是小根堆
后序遍历:
左右根
postorder(2i+1)
postorder(2i+2)
printf(“%d”,level[i]);
3. AC代码
1 |
|