An operator delete for a binary heap data structure is to be designed to delete the item in the -th node. Assume that the heap is implemented in an array and refers to the -th index of the array. If the heap tree has depth (number of edges on the path from the root to the farthest leaf ), then what is the time complexity to re-fix the heap efficiently after the removal of the element?
View worked solution
Answer: B
To delete an element at the -th index of a binary heap implemented as an array, we perform the following steps:
- Replace the element at index with the last element of the heap (at index ).
- Reduce the heap size by .
- Restore the heap property (re-fix the heap) at index :
- If the replaced element is larger than its parent (in a max-heap), we bubble it up towards the root (heapify-up). This takes at most time, where is the depth of the tree.
- If the replaced element is smaller than its children, we bubble it down towards the leaves (heapify-down). This also takes at most time.
Thus, the overall time complexity to re-fix the heap is bounded by the depth of the tree, which is .
Why it is not :
In the worst case (for example, when we delete the root element), the replacement element must be bubbled down all the way to a leaf node. This requires traversing a path of length , taking operations. Therefore, the time complexity is but not .
Free practice · Your answers on this page are not saved.
