algoritmauzmanı
Sign in
TREN
7.2Heap with Linked Nodes
Lesson 7.2.3

Remove the minimum: sift down

This lesson does array removal with linked nodes. The idea is the same: the smallest value at the root is taken, the last value takes its place, and that value is sifted down. In the array the last element was items[count - 1], and decreasing count was enough to delete it. In a linked structure the last node has to be found, detached from its parent, and its memory given back.

What you will learn
  • How to find the last node and detach it from the correct side of its parent
  • Why removing from a one-node heap is a separate case
  • How sift down is written with pointers
7 minTime O(log n)Memory O(1)C · Java · Python

1Idea

The smallest value is in the root's data field; it is saved first. The last node is at position count and is found with nodeAt. Its value is written to the root. Now the last node is no longer needed: its parent's left or right field is set to NULL, the node is freed and count goes down.

Which field becomes NULL? If the last node is its parent's left child, left; if the right child, right. The code tells by comparing with the node itself: last->parent->left == last. Checking whether the position number is odd or even gives the same answer.

If the last node has no parent, the heap has a single node and that node is the root. Its value has already been taken; the root is freed and root becomes NULL. Sift down does nothing when called with a NULL node.

Sift down is the same as in the array version: find the smaller of the two children; if it is smaller than the node's value, swap the values and go down a level. The question "is there a child?" is asked with left < count in the array and with n->left != NULL here.

Freeing the last node without first copying its value to the root, or without reading its value at all, is a common slip. The order matters: save the root's value, write the last value to the root, and only then detach and free the node.

2Step by step

The heap in the drawing is 5, 20, 10, 40, 50, 30, 15, the result of the insertion lesson. We remove the smallest value, 5.

5value51202103404505306157151101153rootlastnsmallest
  1. Start. The heap has 7 nodes; the root holds 5.
  2. The 5 at the root is copied into value. The last node is found with nodeAt(7): the node holding 15.
  3. The last node's value, 15, is written to the root. The last node is no longer needed.
  4. The last node is its parent's right child: the parent's right field becomes NULL, the node is freed and count becomes 6.
  5. Sift down starts at the root. The children are 20 and 10; the smaller is 10, which is smaller than 15.
  6. 15 and 10 are swapped; n goes down to node 3.
  7. 15's only child, 30, is not smaller: the loop stops. The root holds 10; the function returns 5.

struct HeapNode {    int data;    struct HeapNode* left;    struct HeapNode* right;    struct HeapNode* parent;}; struct Heap {    struct HeapNode* root;    int count;}; struct HeapNode* nodeAt(struct Heap* h, int k) {    if (k < 1 || k > h->count) return NULL;    int bit = 1;    while (bit * 2 <= k) bit *= 2;    struct HeapNode* n = h->root;    for (bit /= 2; bit > 0; bit /= 2) n = (k & bit) ? n->right : n->left;    return n;} void siftDown(struct HeapNode* n) {    while (n != NULL) {        struct HeapNode* smallest = n;        if (n->left != NULL && n->left->data < smallest->data) smallest = n->left;        if (n->right != NULL && n->right->data < smallest->data) smallest = n->right;        if (smallest == n) return;        // not larger than either child        int temp = n->data;               // swap the values        n->data = smallest->data;        smallest->data = temp;        n = smallest;    }} bool removeMin(struct Heap* h, int* value) {    if (h->count == 0) return false;               // heap is empty    *value = h->root->data;                        // the minimum is at the root    struct HeapNode* last = nodeAt(h, h->count);    h->root->data = last->data;                    // the last value to the root    if (last->parent == NULL) h->root = NULL;      // there was only one node    else if (last->parent->left == last) last->parent->left = NULL;    else last->parent->right = NULL;    free(last);    h->count--;    siftDown(h->root);    return true;}
class HeapNode {    int data;    HeapNode left, right, parent;    HeapNode(int data) { this.data = data; }} class LinkedHeap {    HeapNode root;    int count = 0;     HeapNode nodeAt(int k) {        if (k < 1 || k > count) return null;        int bit = 1;        while (bit * 2 <= k) bit *= 2;        HeapNode n = root;        for (bit /= 2; bit > 0; bit /= 2) n = (k & bit) != 0 ? n.right : n.left;        return n;    }     void siftDown(HeapNode n) {        while (n != null) {            HeapNode smallest = n;            if (n.left != null && n.left.data < smallest.data) smallest = n.left;            if (n.right != null && n.right.data < smallest.data) smallest = n.right;            if (smallest == n) return;        // not larger than either child            int temp = n.data;                // swap the values            n.data = smallest.data;            smallest.data = temp;            n = smallest;        }    }     int removeMin() {        if (count == 0) throw new IllegalStateException("heap is empty");        int value = root.data;                     // the minimum is at the root        HeapNode last = nodeAt(count);        root.data = last.data;                     // the last value to the root        if (last.parent == null) root = null;      // there was only one node        else if (last.parent.left == last) last.parent.left = null;        else last.parent.right = null;        count--;        siftDown(root);        return value;    }}
class HeapNode:    def __init__(self, data):        self.data = data        self.left = None        self.right = None        self.parent = None class LinkedHeap:    def __init__(self):        self.root = None        self.count = 0     def node_at(self, k):        if k < 1 or k > self.count:            return None        bit = 1        while bit * 2 <= k:            bit *= 2        n = self.root        bit //= 2        while bit > 0:            n = n.right if k & bit else n.left            bit //= 2        return n     def sift_down(self, n):        while n is not None:            smallest = n            if n.left is not None and n.left.data < smallest.data:                smallest = n.left            if n.right is not None and n.right.data < smallest.data:                smallest = n.right            if smallest is n:                return  # not larger than either child            n.data, smallest.data = smallest.data, n.data  # swap the values            n = smallest     def remove_min(self):        if self.count == 0:            raise IndexError("heap is empty")        value = self.root.data  # the minimum is at the root        last = self.node_at(self.count)        self.root.data = last.data  # the last value to the root        if last.parent is None:            self.root = None  # there was only one node        elif last.parent.left is last:            last.parent.left = None        else:            last.parent.right = None        self.count -= 1        self.sift_down(self.root)        return value

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(log n)

Finding the last node is O(log n), and sift down takes at most the height of the tree, O(log n). Total O(log n).

Memory
O(1)

A few variables are enough. One node's memory is given back.

The array version is O(log n) too, but it reaches the last element directly with items[count - 1] and has nothing to free. The linked version calls free on every removal.

4Common mistake

A common mistake is freeing the last node but leaving its parent's link in place:

h->root->data = last->data;free(last);   // wrong: last->parent->right still points to the freed nodeh->count--;

The parent's right field now points to memory that has been given back: a . When sift down reads it, the program crashes or sees a meaningless value. Set the link to NULL first, then free the node.

5Try it

A linked heap has 6 nodes. When the minimum is removed, which node is freed and which field of its parent becomes NULL?

Show the answer

The answer is A. The last node is at position count = 6. Its parent is 6 / 2 = 3, and since 6 is even it is the left child. The root is not freed; only its value changes.

What happens when you remove from a linked heap with one node?

Show the answer

The answer is A. The last node is the root itself and its parent field is NULL. In that case the code sets root to NULL, frees the node, and count becomes 0.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.