假定是最小堆。
伪代码:
1, Delete a node from the array
(this creates a "hole" and the tree is no longer "complete")
2. Replace the deletion node
with the "fartest right node" on the lowest level
of the Binary Tree
(This step makes the tree into a "complete binary tree")
3. Heapify (fix the heap):
if ( value in replacement node < its parent node )
Filter the replacement node UP the binary tree
else
Filter the replacement node DOWN the binary tree
JAVA:
public double remove( int k )
{
int parent;
double r; // Variable to hold deleted value
r = a[k]; // Save return value
a[k] = a[NNodes]; // Replace deleted node with the right most leaf
// This fixes the "complete bin. tree" property
NNodes--; // One less node in heap....
parent = k/2;
/* =======================================================
Filter a[k] up or down depending on the result of:
a[k] <==> a[k's parent]
======================================================= */
if ( k == 1 /* k is root */ || a[parent] < a[k] )
HeapFilterDown(k); // Move the node a[k] DOWN the tree
else
HeapFilterUp(k); // Move the node a[k] UP the tree
return r; // Return deleted value...
}
HeapFilterDown, HeapFilterUp就是下沉和上浮操作。
参考:
http://www.mathcs.emory.edu/~cheung/Courses/171/Syllabus/9-BinTree/heap-delete.html