Heap
A heap is a special tree-based data structure that satisfies two rules:
1. Heap Property
Depending on the type of heap:
Min-Heap
Every parent node is less than (≤) it's children.
The smallest element is always at the root.
Max-Heap
Every parent node is ≥ its children.
The largest element is always at the root.
It does not require a fully sorted structure, only the parent/child relationship must follow the rule.
2. Complete Binary Tree Property
A heap is always a complete binary tree, meaning:
It is filled level by level, from left to right.
No gaps are allowed except possibly at the last level.
This makes it easy to store a heap inside an array without needing pointers.
How a Heap Is Stored in an Array
For a node at index i:
Left child = index
2iRight child = index
2i + 1Parent = index
i // 2
This mapping is why heaps work efficiently inside arrays.
Heap Insert
| Insert/Create Heap |
Heap Deletion
Python Syntax:
import heapq
nums=[5 3, 8, 1]
heapq.heapify(nums)
heapq.heappush(nums,2)
smallest = heapq.heappop(nums)
#Max heap (negation)
maxheap=[]
heapq.heappush(maxheap, -1 * 5 )
heapq.heappush(maxheap, -1 * 2 )
largest = -1 * heapq.heappop(maxheap)
Comments
Post a Comment