Introduction
Imagine you want to quickly find the smallest or largest item in a collection without sorting everything every time. Min-heaps and max-heaps solve this problem by organizing data so you can access these items instantly.
Imagine a tournament where players compete in matches arranged in a tree. In a min-heap style tournament, the weakest player always wins each match and moves up, so the overall weakest player is at the top. In a max-heap style, the strongest player always wins and reaches the top.
┌───────┐
│ Root │
│(Min or│
│ Max) │
└───┬───┘
│
┌───────┴───────┐
│ │
┌───┴───┐ ┌───┴───┐
│ Child │ │ Child │
│ 1 │ │ 2 │
└───────┘ └───────┘
Each parent node connects to two children, maintaining the min-heap or max-heap property.import heapq # Min-heap example min_heap = [] heapq.heappush(min_heap, 5) heapq.heappush(min_heap, 3) heapq.heappush(min_heap, 8) print('Min-heap root:', min_heap[0]) # Max-heap example using negative values max_heap = [] heapq.heappush(max_heap, -5) heapq.heappush(max_heap, -3) heapq.heappush(max_heap, -8) print('Max-heap root:', -max_heap[0])