CJCoding With Joseph
15free / daySign inCreate account

Min Heap

Trees and Heaps

A Min-Heap is a type of binary tree where the smallest value is always at the top (the root), and each parent node is always smaller than or equal to its child nodes.

There are some important rules that define a Min-Heap:

  • The tree must be a complete binary tree. This means all levels of the tree are filled except maybe the last, and nodes are filled from left to right.

  • Every parent node must be less than or equal to its children.

  • The smallest value is always at the root.

Here’s a quick example:

         2
       /   \
      5     3
     / \   /
    9   6 8


How is a Min-Heap Different from a Binary Search Tree?

A Min-Heap is not the same as a BST. Here are the key differences:

1. Ordering:

  • In a BST, the left child must be less than the parent, and the right child must be greater than the parent.

  • In a Min-Heap, the only rule is that the parent is smaller than or equal to its children. It doesn’t matter whether the child is on the left or right.

2. Structure:

  • A BST can be unbalanced and irregular depending on how items are inserted.

  • A Min-Heap is always a complete binary tree. They are very compact and always filled left to right.

3. Use Cases:

  • BSTs are used for fast lookups, insertions, and deletions.

  • Min-Heaps are used when we constantly need access to the smallest item quickly (like in priority queues).


Why Use a Min-Heap?

Min-Heaps are great for situations where you need to:

  • Quickly find or remove the smallest element

  • Keep elements partially sorted

  • Implement priority queues, Dijkstra’s algorithm, and more

They are fast. Insertion and removal take O(log n) time and getting the minimum value takes O(1).


Min Heap Structure

Unlike BSTs or AVLs that are made with nodes and pointers, a Min-Heap is stored using just a simple array (or a vector). We don’t need to create any structs or pointers to manage left and right children.

This works because Min-Heaps are always complete binary trees. That means:

  • Every level of the tree is completely filled, except maybe the last one.

  • The last level fills from left to right.

Thanks to this structure, we can easily calculate where any node’s children or parent are using simple math based on the node’s index in the array. If a node is stored at index i, then:

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 42 more lessons in Data Structures & Algorithms.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • Mock exams marked by hand, with feedback
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel anytime.