2.4 Node deletion

Generally speaking, we do not delete any node from a heap. The node to remove from a heap is usually the root of the heap. Let us assume the serial number of the last leaf in a heap is n.

The deletion process starts with saving the value of the root node (for returning). Then, the value of node n is copied as the value of the root. The serial number of the last leaf becomes n 1.

After this is done, the root most likely is not greater than or equal to all its children. If that is the case, then we choose the child with the maximum value and swap the values of that child and the root.

We then perform this operation again with the child that just got its value swapped with the root. This process terminates when there is no need to swap the value of a node and one of its children.

The logic to remove a value (that of the root node) from a heap is illustrated in listing 2.


Listing 2:heapremove
 
1define sub heap_remove 
2  by reference t : heap 
3  return type : value_type 
4  local r : value_type 
5  local n : node 
6  n t.root 
7  rv(n
8  v(n)v(t.last
9  remove the last leaf from t 
10  while n has a child c such that v(c)> v(ndo 
11    let c be the child of n with the max value 
12    swap the values of n and c 
13    n c 
14  end while 
15  return r 
16end define sub

In the worst case, removing the root from a heap is a Θ(log(n)) operation, where n is the number of items in the heap.