Heap Data Structure
A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Generally,
Heaps can be of two types:
1. Max-Heap: In a Max-Heap the key present at the root node must be greatest among the
keys present at all of its children. The same property must be recursively true for all sub-
trees in that Binary Tree.
2. Min-Heap: In a Min-Heap the key present at the root node must be minimum among the
keys present at all of its children. The same property must be recursively true for all sub-
trees in that Binary Tree.
Insertion in Heaps
The insertion operation is also similar to that of the deletion process.
Given a Binary Heap and a new element to be added to this Heap. The task is to insert the new
element to the Heap maintaining the properties of Heap.
Process of Insertion: Elements can be inserted to the heap following a similar approach as
discussed above for deletion. The idea is to:
• First increase the heap size by 1, so that it can store the new element.
• Insert the new element at the end of the Heap.
• This newly inserted element may distort the properties of Heap for its parents. So, in
order to keep the properties of Heap, heapify this newly inserted element following a
bottom-up approach.
Illustration:
Suppose the Heap is a Max-Heap as:
10
/ \
5 3
/ \
2 4
The new element to be inserted is 15.
Process:
Step 1: Insert the new element at the end.
10
/ \
5 3
/\ /
2 4 15
Step 2: Heapify the new element following bottom-up approach.
-> 15 is more than its parent 3, swap them.
10
/ \
5 15
/ \ /
2 43
-> 15 is again more than its parent 10, swap them.
15
/ \
5 10
/\ /
2 4 3
Therefore, the final heap after insertion is:
15
/\
5 10
/ \ /
2 4 3
Deletion in Heap
Given a Binary Heap and an element present in the given Heap. The task is to delete an element
from this Heap.
The standard deletion operation on Heap is to delete the element present at the root node of the
Heap. That is if it is a Max Heap, the standard deletion operation will delete the maximum
element and if it is a Min heap, it will delete the minimum element.
Process of Deletion:
Since deleting an element at any intermediary position in the heap can be costly, so we can
simply replace the element to be deleted by the last element and delete the last element of the
Heap.
• Replace the root or element to be deleted by the last element.
• Delete the last element from the Heap.
• Since, the last element is now placed at the position of the root node. So, it may not
follow the heap property. Therefore, heapify the last node placed at the position of root.
Illustration:
Suppose the Heap is a Max-Heap as:
10
/ \
5 3
/ \
2 4
The element to be deleted is root, i.e. 10.
Process:
The last element is 4.
Step 1: Replace the last element with root, and delete it.
4
/ \
5 3
/
2
Step 2: Heapify root.
Final Heap:
5
/ \
4 3
/
2