Binary Heap as a Tree — Heap Property Visualization
Visualize a binary heap as a complete binary tree. Understand the max-heap and min-heap properties, heap operations, and how the array representation maps to tree structure.
Detailed Explanation
Binary Heap as a Tree
A binary heap is a complete binary tree that satisfies the heap property: in a max-heap, every parent is greater than or equal to its children; in a min-heap, every parent is less than or equal to its children.
Max-Heap Example
Tree view: Array: [90, 70, 80, 30, 50, 60, 40]
90
/ \
70 80
/ \ / \
30 50 60 40
Parent of i: floor((i-1)/2)
Left child of i: 2i + 1
Right child of i: 2i + 2
Min-Heap Example
10
/ \
20 15
/ \ / \
30 25 50 40
Every parent ≤ its children
Heap Operations
Insert (Bubble Up / Sift Up):
- Add the new element at the end (next available position)
- Compare with parent; if it violates the heap property, swap with parent
- Repeat until the property is restored or the root is reached
- Time: O(log n)
Extract Max/Min (Bubble Down / Sift Down):
- Remove the root (max or min element)
- Move the last element to the root position
- Compare with children; swap with the larger (max-heap) or smaller (min-heap) child
- Repeat until the property is restored
- Time: O(log n)
Heapify (Build Heap):
- Start from the last non-leaf node (index n/2 - 1)
- Sift down each node
- Time: O(n) — not O(n log n) due to the decreasing height of subtrees
Why Complete Binary Tree?
The complete binary tree structure ensures:
- Minimum height for the number of nodes: O(log n)
- Efficient array representation with no wasted space
- O(1) access to the last element for insert/delete
Heap vs BST
| Property | Heap | BST |
|---|---|---|
| Ordering | Parent vs children only | Left < parent < right |
| Structure | Complete binary tree | Any shape |
| Find min/max | O(1) | O(h) |
| Search | O(n) | O(h) |
| Insert | O(log n) | O(h) |
Use Case
Binary heaps are used in priority queues (operating system task scheduling, event-driven simulation), heap sort (guaranteed O(n log n) in-place sorting), Dijkstra's shortest path algorithm, Huffman coding (building the optimal prefix code), and the median of a data stream problem (using a max-heap and min-heap together).