0

what are couple of scenarios where you will be using a binary heap instead of a binary search tree?

I have a basic understanding of each structure. Id like your input on that if possible.

lam97
  • 17
  • 9

2 Answers2

0

One scenario where it's helpful to use a binary heap instead of a binary search tree is in the case of a priority queue. Priority queues require certain functionalities such as accessing the priority element, inserting elements, and removing top priority elements. Heaps can do this in O(1), O(log n), and O(log n) respectively. However, certain types of binary search trees can also do this (see: self balancing search trees). Beyond that, priority queues are also easier to implement with binary heaps, don't require extra space for pointers, and building them takes O(n) time versus the O(n log n) for self balancing binary search trees.

Another scenario where a binary heap would be more useful than a binary search tree is if you need random order removal and have access to the index of the heap objects.

Overall, binary heaps come in handy with how they use less space (by a constant factor) and can be implemented with a single array without worrying about pointers. However, at the end of the day, your choice really depends on whatever application you're trying to implement.

Jaya
  • 9
  • 2
0

Binary heaps are very useful when you need to find the smallest or biggest element in a data set. A binary heap will always have either the smallest or largest element in the root node, so it can be retrieved in constant (O(1)) time. Binary heaps can be used to maximize the efficiency of some algorithms, like prim's minimum spanning tree algorithm and dijkstra's shortest path algorithm. These algorithms can both use binary heaps to quickly find the smallest edge available in the graphs that they are run on.

The advantage to a binary search tree is that the elements can be accessed in order easily, however it requires a lot more overhead to manage a binary search tree than a binary heap. So if A binary search tree can also be inefficiently made depending on how and what elements are added to it. If the tree is not balanced, then many of the efficiency advantages of using a binary search tree go away. Using red black trees, or abl trees can fix this, but at the cost of the overhead of maintaining balance.

In short, a binary heaps are better when one only needs to find the largest or smallest element in a data set, as it is easy to access and they are cheaper to manage. A binary search tree contains the specific order of the elements, but they take more to manage.

qchud
  • 11
  • 1