Heap

About

It is a Binary Tree where every child is:

  • Smaller than the current node. (Max Heap)

  • Larger than the current node. (Min Heap)

circle-exclamation
circle-check
circle-info

Whenever a node is added or deleted, the Tree MUST be ajusted.

Used in priority queues for example.

Drawing

Node sequence of Heap

Nodes of the Heap follow a sequence to defines the first and last node of the Tree.

This sequence also helps on insertion and deletion, since inserted elements are added to the end (or last position), and deleted elements are deleted at position 0 (first position).

Drawing

Inserting an element (Tree)

  1. Elements are added at either:

    • The last level (height) where you have an empty space. (Usually from left to right)

    • New created level. (Usually from left to right)

  2. Then check the added element XX against AncestorXAncestor_X to see if it satisfy Heap conditions.

  3. Repeat 2. until Heap conditions are satisfied.

circle-info

The repeat 2. process is called Heapify Up, where the added node thies to bubble up in the Tree.

circle-info

Runs on O(logN)O(log N ) since the Tree is always balanced.

Deleting an element (Tree)

  1. The top element is the one deleted.

  2. Then the very last node XX in the Tree takes the place of the top node.

  3. The XX node is checked against:

    1. In a MinHeap, the smallest of XchildX_{child}, then if Xchild<XX_{child} < X they swapp positions.

    2. In a MaxHeap, the highest of XchildX_{child}, then if they swapp positions.

  4. Repeat 3. until Heap conditions are satisfied.

circle-info

The repeat 3. process is called Heapify Down, where the node that took place of the deleted node tries to bubble down in the Tree.

circle-info

Runs on O(logN)O(log N ) since the Tree is always balanced.

Implementing Heap with Arrays

Heaps can easily be implemented with Arrays Data Structures, and thus facilitating the removal of nodes.

You simulate left and right childs and parent nodes in Arrays with the following formulas: (where i is the current node index being looked)

  • left child: 2i+12i + 1

  • right child: 2i+22i + 2

  • parent node: (i1)2\lfloor\frac{(i-1)}{2}\rfloor

Last updated