Home  Dsa   Why min and ...

why min and max heaps use arrays instead of nodes

Let’s unpack why heaps use arrays instead of pointers or linked nodes — and why that’s brilliantly efficient.


🌳 1. Heap = Complete Binary Tree

A heap is a complete binary tree, meaning:

Every level is completely filled,

Except possibly the last level, which is filled from left to right.

Example (Min-Heap):

    10
   /  \
 20    30
/ \   /

40 50 60


💡 2. Perfect Fit for an Array

Because it’s complete, there are no gaps — you can store all nodes level by level in an array.

👉 So instead of storing Node objects with left and right pointers, we can just use index math.


🧮 3. Index Relationships

If a node is at index i (0-based index):

Relationship Formula

Left child 2 * i + 1 Right child 2 * i + 2 Parent (i - 1) / 2

So for:

Index: 0 1 2 3 4 5 Value: 10 20 30 40 50 60

Relationships:

root = arr[0] = 10

left(0) = arr[1] = 20

right(0) = arr[2] = 30

parent(3) = arr[1]

✅ This simple math eliminates the need for pointers!


⚡ 4. Why It’s Efficient

➤ Space Efficiency

No need to store left and right pointers. Every node just sits in the array — no overhead.

➤ Cache Efficiency

Arrays are contiguous in memory, so traversing is fast due to CPU caching. Pointer-based trees (like BSTs) are scattered in memory → slower traversal.

➤ Simplicity in Implementation

Insertions and deletions just mean:

Add/remove last element

Swap using parent/child index formulas

Maintain heap property (heapify up/down)

Example: Heapify-Up

void heapifyUp(int i) { int parent = (i - 1) / 2; while (i > 0 && arr[i] < arr[parent]) { swap(i, parent); i = parent; parent = (i - 1) / 2; } }

No tree rotations or pointer updates!


🧠 5. When NOT to Use Array for Tree

When the tree is not complete (e.g., a sparse BST), array indexing wastes space — because gaps appear.

For example, a BST like this:

    10
      \
       20
         \
          30

Would need an array with lots of empty spaces.

So:

Complete tree (Heap) → ✅ use array

Sparse tree (BST, AVL, etc.) → ❌ use pointers/nodes


🧩 Summary

Property Heap (Array) Linked Tree

Structure Complete binary tree Any binary tree Storage Contiguous array Node objects with pointers Space overhead Low High (extra pointers) Cache performance Excellent Poor Suitable for Priority Queue, Heap Sort BST, Trie, etc.

Published on: Oct 19, 2025, 08:21 AM  
 

Comments

Add your comment