A heap is a binary tree that satisfies two properties:
-
Structural Property:
- It is an almost complete binary tree. Level i has
$2^i$ nodes. - The nodes are inserted from left to right (left-filled)
- The last level will never be fully filled.
- It is an almost complete binary tree. Level i has
-
Parental Dominance: Every node will be more dominant than its children node. The manner of dominance depends on the type of heap.
- In a max heap, each node is greater in value than all its children nodes.
- In a min heap, each node is smaller in value than all its children nodes.
- Construct a binary tree for the given elements.
- From the last level, go upwards checking if the parent nodes at every level are greater/smaller than its children nodes.
- If necessary, swap appropriately. When a swap is performed between two nodes, recheck the subtree with the swapped node as root.
- Add each node in the leaf layer from the left (left filled property), and swap it upwards into its correct spot.
- This way, instead of constructing a binary tree and converting it into a heap, we build a heap while inserting the elements in the first place.
⚠️ Even when the same elements are used to construct a heap, the two approaches may give different results.