目录
1.什么是最大堆
最大堆就是根节点值是所有节点中最大的,且其左右子树也分别是最大堆这样的树。反
之就是最小堆
2.最大堆问题的关键点
最大堆是用数组存储的完全二叉树,利用了完全二叉树的父节点和子节点的关系性质,
和完全二叉树本身插入和删除的性质(即要保证插入和删除操作后其还是完全二叉树
结构)。
举个最大堆、最小堆的例子
最大堆问题的关键点就是如何在插入和删除后,将其调整成一个完全二叉树结构。
插入操作:因为插入操作前树已经是完全二叉树,所有新元素只能插在最后的位置,
而最后的位置就是当前树的节点个数加1后指向的位置。有可能新插入的节点值比它
的父节点要大,因此要和父节点逐层比较,直到比父节点小,就找到了插入的位置。
删除操作:因为根节点是最大的,拿走根节点后破坏了完全二叉树的结构,需要填补
一个上来,在不破坏子树完全二叉树的条件下,只能用最后一个元素来填补。而填补
上来的节点值可能比儿子节点小,因此要逐层和左右节点的较大子节点比较,直到大
于子节点。
3.怎么用最大堆
先放上最大堆的建立,销毁,插入和删除操作,具体应用在堆排序中。
typedef int ElementType;
//data struct
typedef struct __heap{
ElementType *domain;
int size;
int capacity;
}*heapPtr;
#define isHeapFull(h) \
(h->size == h->capacity)? true:false;
#define isheapEmpty(h) \
(h->size == 0)? true:false;
/*
*The insertion rules of new nodes must satisfy the
*properties of complete binary tree
*/
int InsertHeap(heapPtr hp,ElementType item)
{
if(isHeapFull())
return -1;
int i = ++hp->size;//get position of new node
for(i; i>=1 && hp->domain[i/2] < item;i = hp->size/2)//new node compare with father
hp->domain[i] = hp->domain[i/2];
hp->domain[i] = item;
}
/*
*get Max item from heap,and Delete it .Note: we need take the
* last one as root node, in order to ensure this heap
*suitable the defination of Complete Binary Tree,then make it
*to maxHeap
*/
ElementType DeleteHeap(heapPtr hp)
{
ElementType Mx,x;
int parent,child;
if(isHeapEmpty())
return -1;
Mx = hp->domain[1];
x = hp->domain[hp->size--];
for(parent = 1;2*parent <=hp->size;parent = child)
{
child = 2*parent;
if((child < hp->size) && hp->domain[child] < hp->domain[child+1])
child++;//get the big one because we are the max heap
if(x < hp->domain[child])
hp->domain[parent] = hp->domain[child];
else
{
hp->domain[parent] = x;
break;
}
}
return Mx;
}
/*
*create original heap structure
*/
heapPtr CreateHeap(int size)
{
heapPtr hp = (heapPtr)calloc(1,sizeof(__heap));
if(!hp)
return NULL;
hp->domain = (ElementType*)calloc(1,sizeof(ElementType));
if(!hp->domain)
goto error;
hp->size = 0;
hp->capacity = size;
return hp;
error:
free(hp);return NULL;
}
/*
*Destroy heap ,free area
*/
void DestroyHeap(heapPtr hp)
{
assert(hp);
if(hp->domain)
free(hp->domain);
free(hp);
}
/*
*fix an subHeap to Mx heap
*/
void fixMxHeap(heapPtr hp, int pos)
{
ElementType x;
int parent,child;
x = hp->domain[pos];
for(parent = p;2*parent <=hp->size;parent = child)
{
child = 2*parent;
if((child < hp->size) && hp->domain[child] < hp->domain[child+1])
child++;//get the big one because we are the max heap
if(x < hp->domain[child])
hp->domain[parent] = hp->domain[child];
else
{
hp->domain[parent] = x;
break;
}
}
return Mx;
}
/*
*make the heap from The parent of last node to Mx heap until the whole heap is Mx heap
*/
void BuildHeap(heapPtr hp)
{
int i;
for(i = hp->size/2; i>0; i--)
fixMxHeap(hp,i);
}