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

Insert: sift up

This lesson does array insertion with linked nodes. The steps are the same: the new value goes into the next free place, then climbs while it is smaller than its parent. The only change is finding the next free place. In the array it was cell items[count]; here the new node's parent is found with nodeAt.

What you will learn
  • How to find the new node's parent, and whether it becomes a left or right child, from its position number
  • That sift up swaps the values, not the nodes
  • Why inserting into a linked heap still takes O(log n)
7 minTime O(log n)Memory O(1)C · Java · Python

1Idea

If the heap has count nodes, the new node's position is count + 1. The parent of that position is at (count + 1) / 2. The code increases count first, so the new position is count and its parent is count / 2. The parent is found with nodeAt. If the position is even the new node becomes a left child, if odd a right child, because position k has its children at 2k and 2k+1.

Once the new node is attached the tree is complete, but the may be broken. Sift up works as in the array, only with a pointer instead of an index: if n->parent is not NULL and the parent's value is larger, the two values swap and n climbs to the parent.

Swapping the nodes themselves is possible too, but every swap would have to update six different pointers: the left, right and parent fields of both nodes, the parent fields of the children, and the grandparent's link. Swapping only the data fields gives the same result in three lines. The nodes stay where they are and the values move.

The first insertion into an empty heap is a separate case: the new node becomes the root, it has no parent, and there is nothing to sift.

2Step by step

The heap in the drawing is 10, 20, 15, 40, 50, 30. We insert 5 into it; it is the same example as in the array lesson. The numbers under the nodes are position numbers.

101202153404505306575315751103rootnodeparentn
  1. Start. The heap has 6 nodes; count is 6.
  2. insert(5). The new node is created and count becomes 7. The new position is 7; its parent is 7 / 2 = 3. nodeAt(3) returns the node holding 15.
  3. 7 is odd, so the new node becomes 15's right child, and its parent field points to 15.
  4. Sift up starts with n at the new node. The parent's value, 15, is larger than 5.
  5. The values are swapped: node 3 now holds 5 and node 7 holds 15. The nodes did not move. n climbs to the parent.
  6. The new parent is the root: 10 is larger than 5.
  7. The values are swapped again: 5 at the root, 10 in node 3. n climbs to the root.
  8. The root's parent field is NULL: the loop stops. The result is the same as in the array lesson: 5, 20, 10, 40, 50, 30, 15.

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 siftUp(struct HeapNode* n) {    while (n->parent != NULL && n->parent->data > n->data) {        int temp = n->data;            // swap the values, not the nodes        n->data = n->parent->data;        n->parent->data = temp;        n = n->parent;    }} bool insert(struct Heap* h, int value) {    struct HeapNode* node = malloc(sizeof(struct HeapNode));    if (node == NULL) return false;    // out of memory    node->data = value;    node->left = NULL; node->right = NULL; node->parent = NULL;    h->count++;    if (h->count == 1) {        h->root = node;                // empty heap: it becomes the root        return true;    }    struct HeapNode* parent = nodeAt(h, h->count / 2);    node->parent = parent;    if (h->count % 2 == 0) parent->left = node;    // even position: left    else parent->right = node;                     // odd position: right    siftUp(node);    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 siftUp(HeapNode n) {        while (n.parent != null && n.parent.data > n.data) {            int temp = n.data;             // swap the values, not the nodes            n.data = n.parent.data;            n.parent.data = temp;            n = n.parent;        }    }     void insert(int value) {        HeapNode node = new HeapNode(value);        count++;        if (count == 1) {            root = node;                   // empty heap: it becomes the root            return;        }        HeapNode parent = nodeAt(count / 2);        node.parent = parent;        if (count % 2 == 0) parent.left = node;    // even position: left        else parent.right = node;                  // odd position: right        siftUp(node);    }}
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_up(self, n):        while n.parent is not None and n.parent.data > n.data:            # swap the values, not the nodes            n.data, n.parent.data = n.parent.data, n.data            n = n.parent     def insert(self, value):        node = HeapNode(value)        self.count += 1        if self.count == 1:            self.root = node  # empty heap: it becomes the root            return        parent = self.node_at(self.count // 2)        node.parent = parent        if self.count % 2 == 0:            parent.left = node  # even position: left        else:            parent.right = node  # odd position: right        self.sift_up(node)

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

3Complexity

Time
O(log n)

Finding the parent is O(log n), and sift up takes at most the height of the tree, O(log n). Total O(log n).

Memory
O(1)

One malloc for the new node; besides that, a few variables.

Inserting into a linked binary tree searched for the first free place with a queue and took O(n). In a heap the number of nodes is known, so the place comes from the position number with no queue.

4Common mistake

A common mistake is forgetting to set the new node's parent field:

if (h->count % 2 == 0) parent->left = node;else parent->right = node;siftUp(node);   // node->parent is still NULL

Then sift up takes the new node for the root and stops at once; the small value stays down below and the heap property breaks. The link from child to parent must be set as well as the link from parent to child.

5Try it

A linked heap has 9 nodes. Which child of which node does the new node become?

Show the answer

The answer is A. The new position is 10. Its parent is 10 / 2 = 5. 10 is even, so it is the left child.

Why does sift up swap the values and not the nodes?

Show the answer

The answer is A. What matters for a heap is which value sits in which position. A value swap achieves that; swapping nodes would mean fixing the pointers of both nodes, their children and their parent one by one.

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