堆问题汇总
目录
定义
定义: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.
即n个元素的序列,当且仅当满足下面关系时,称之为堆。
小顶堆Min Heap 或 大顶堆Max Heap
检查是大顶堆、小顶堆或者不是堆
自顶向下,直到最后一个有孩子的结点,检查每一个结点与其孩子结点是否满足上述定义中的公式
int flag=arr[1]>arr[2]?-1:1; //-1为大顶堆,1为小顶堆,0不是堆
for(int k=1;k<=N/2;k++){ //从1开始,N/2为最后一个有孩子的结点
//判断是否满足公式,2*k+1不能越界
if(flag==-1 && ( arr[k]<arr[2*k] || (arr[k]<arr[2*k+1] && 2*k+1<=N) )){
flag=0;
}else if(flag==1 && (arr[k]>arr[2*k] || (arr[k]>arr[2*k+1] && 2*k+1<=N) )){
flag=0;
}
}
if(flag==0){
printf("Not Heap\n");
}else{
printf("%s\n",flag==-1?"Max Heap":"Min Heap");
}