A heap is a binary tree that meets the heap property. Heap can be of two types:
Min heap: The element of each node is larger than or equal to the element at its parent. The node with the lowest value is the root.
Max heap: The element of each node is smaller than the element at its parent. The highest value element is at the root.
Building a heap from an array ensures that the heap order property is maintained after every input. The input is checked if it is smaller than its parent. If it's not, it is swapped.
When it comes to deleting an element from the max heap, there are two cases:
Case-01: Deletion of the leaf nodes
This case is straightforward to handle. We delete/disconnect the leaf node from the max heap in this case. After deleting the leaf node, we don’t need to change any value in the max heap.
Case-02: Deletion of some other node
This case is strenuous as deleting a node other than the leaf node disturbs the heap properties. This case takes two steps for deletion:
Delete the selected element from the given heap tree and replace the value of the last node with deleted node.
Check the max heap properties for the entire heap and keep calling the heapify()
function until we get the max heap.
Let's visualize it from an example. In this example, we delete the root node:
Here's the step-by-step implementation of deleting a node from the max heap:
void deleteNode(int array[], int node) //function for deleting node{int i=0;for (i = 0; i < size; i++){if (node == array[i]) //finding selected nodebreak;}swap(&array[i], &array[size - 1]); //swapping with last nodesize -= 1; //decrementing size after deleting nodefor (int i = size / 2 - 1; i >= 0; i--){heapify(array, i); //heapifying}}// Driver Codeint main(){int array[] = {1, 5, 6, 8, 9, 7, 3};size = sizeof(array) / sizeof(array[0]); //sizebuild_heap(array); //creating heapcout << "Heapify Array: ";printArray(array); //print nodedeleteNode(array,9); //deleting root nodecout << "After Deleting root \nHeapify Array: ";printArray(array); //printing nodereturn 0;}
Line 2–9: We define deleteNode()
and use a for
loop to find the desired element in the given max heap array.
Line 11–12: We swap the value of the selected node with the last node and decrement the size.
Line 14–17: We use heapify()
on the array to change the affected values and recreate the max heap.
Free Resources