Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove elements from a binary heap?

As I understand, binary heap does not support removing random elements. What if I need to remove random elements from a binary heap?

Obviously, I can remove an element and re-arrange the entire heap in O(N). Can I do better?

like image 353
Michael Avatar asked Sep 02 '12 06:09

Michael


People also ask

How do you remove a root node from a heap tree?

The rules for removing the root node from a binary heap are: Replace the root node with the lowest, right-most item on the heap. Decrement the count. Sift the new value down the heap to its new position.

What is the algorithm to delete the root key from the heap?

Max Heap Deletion Algorithm Step 1 − Remove root node. Step 2 − Move the last element of last level to root. Step 3 − Compare the value of this child node with its parent. Step 4 − If value of parent is less than child, then swap them.

What is the complexity of removing an element from a heap?

Therefore, Overall Complexity of delete operation is O(log N). In order to obtain the minimum value just return the value of the root node (which is the smallest element in Min Heap), So simply return the element at index 0 of the array.


1 Answers

Yes and no.

The problem is a binary heap does not support search for an arbitrary element. Finding it is itself O(n).

However, if you have a pointer to the element (and not only its value) - you can swap the element with the rightest leaf, remove this leaf, and than re-heapify the relevant sub-heap (by sifting down the newly placed element as much as needed). This results in O(logn) removal, but requires a pointer to the actual element you are looking for.

like image 60
amit Avatar answered Oct 14 '22 05:10

amit