How to delete an element from the max heap

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.

%0 node_1 9 node_2 8 node_1->node_2 node_3 7 node_1->node_3 node_1658064506720 1 node_2->node_1658064506720 node_1658064502420 5 node_2->node_1658064502420 node_1658064536669 6 node_3->node_1658064536669 node_1658064559127 3 node_3->node_1658064559127
Max Heap

Delete operation

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:

  1. Delete the selected element from the given heap tree and replace the value of the last node with deleted node.

  2. 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:

1 of 7

Implementation

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 node
break;
}
swap(&array[i], &array[size - 1]); //swapping with last node
size -= 1; //decrementing size after deleting node
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(array, i); //heapifying
}
}
// Driver Code
int main()
{
int array[] = {1, 5, 6, 8, 9, 7, 3};
size = sizeof(array) / sizeof(array[0]); //size
build_heap(array); //creating heap
cout << "Heapify Array: ";
printArray(array); //print node
deleteNode(array,9); //deleting root node
cout << "After Deleting root \nHeapify Array: ";
printArray(array); //printing node
return 0;
}

Explanation

  • 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

Copyright ©2025 Educative, Inc. All rights reserved