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.
代码如下:
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
vector<int> v;
struct node{
int value;
node* lchild;
node* rchild;
};
node* vn[1009];
node* create(int data[],int n){
node* root=new node;
root->value=data[1];
root->lchild=NULL;
root->rchild=NULL;
vn[1]=root;
for(int i=2;i<=n;i++){
node* now=new node;
now->value=data[i];
now->lchild=NULL;
now->rchild=NULL;
i%2==0?vn[i/2]->lchild=now:vn[i/2]->rchild=now;
vn[i]=now;
}
return root;
}
void postorder(node* root){
if(root==NULL) return;
postorder(root->lchild);
postorder(root->rchild);
v.push_back(root->value);
}
int main(){
int num,n;
cin>>num>>n;
int data[1009];
while(num--){
for(int i=1;i<=n;i++) cin>>data[i];
int isMax=1,isMin=1;
for(int i=2;i<=n;i++){
if(data[i/2]<data[i]) isMax=0;
if(data[i/2]>data[i]) isMin=0;
}
if(isMin==1&&isMax==0) printf("Min Heap\n");
else if(isMin==0&&isMax==1) printf("Max Heap\n");
else printf("Not Heap\n");
node* root=create(data,n);
postorder(root);
for(int i=0;i<v.size();i++) printf("%d%s",v[i],i==v.size()-1?"\n":" ");
v.clear();
}
return 0;
}
其实这几天做的树和堆比较多,所以对于一棵建好的树进行先中后遍历是没有什么问题的,但做这个题的时候我困在了如何用层序遍历序列来建树,这就和之前做的那个题不一样(PAT1155:不需要建数)因为先中后遍历函数的参数为node* root。 刚开始有想过用动态数组放入结点,利用下标来建树等,但后面突然发现根节点不能放在v[0],会增加很多思考及逻辑上的难度,故我放弃了动态数组,直接用了数组。
这个题的解题过程中其实我遇到了一个问题,就是C++程序停止工作。我刚开始以为是数组越界什么的,有尝试进行调试,但我发现我不会dev c++的调试(呜呜呜TAT),所以我直接用/**/定位到了是create函数出错了,我看了半天(发现了之前动态数组的问题),才发现我没有return root. 汗。。。。
下次这些小地方一定要注意!