Why is Binary Heap Preferred over BST for Priority Queue?

A typical Priority Queue requires following operations to be efficient.

  1. Get Top Priority Element (Get minimum or maximum)
  2. Insert an element
  3. Remove top priority element
  4. Decrease Key

A Binary Heap supports above operations with following time complexities:

  1. O(1)
  2. O(Logn)
  3. O(Logn)
  4. O(Logn)

A Self Balancing Binary Search Tree like AVL Tree, Red-Black Tree, etc can also support above operations with same time complexities.

  1. Finding minimum and maximum are not naturally O(1), but can be easily implemented in O(1) by keeping an extra pointer to minimum or maximum and updating the pointer with insertion and deletion if required. With deletion we can update by finding inorder predecessor or successor.
  2. Inserting an element is naturally O(Logn)
  3. Removing maximum or minimum are also O(Logn)
  4. Decrease key can be done in O(Logn) by doing a deletion followed by insertion. See this for details.

So why is Binary Heap Preferred for Priority Queue?

Is Binary Heap always better?
Although Binary Heap is for Priority Queue, BSTs have their own advantages and the list of advantages is in-fact bigger compared to binary heap.

This article is contributed by Vivek Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

Article Tags :
Practice Tags :