When should I use a TreeMap over a PriorityQueue and vice versa?

Viewed 24729

Seems they both let you retrieve the minimum, which is what I need for Prim's algorithm, and force me to remove and reinsert a key to update its value. Is there any advantage of using one over the other, not just for this example, but generally speaking?

11 Answers

I find TreeMap to be useful, when there is a need to do something like:

  • find the minimal/least key, which is greater equal some value, using ceilingKey()
  • find the maximum/greatest key, which is less equal some value, using floorKey()

If the above is not required, and it's mostly about having a quick option to retrieve the min/max - PriorityQueue might be preferred.

Their difference on time complexity is stated clearly in Erickson's answer.

On space complexity, although a heap and a TreeMap both take O(n) space complexity, building them in actual programs takes up different amount of space and effort.

Say if you have an array of numbers, you can build a heap in place with O(n) time and constant extra space. If you build a TreeMap based on the given array, you need O(nlogn) time and O(n) extra space to accomplish that.

One more thing to take into consideration, PriorityQueue offers an api which return the max/min value without removing it, the time complexity is O(1) while for a TreeMap this will still cost you O(logn)

This could be clear advantage in case of readonly cases where you are only interested in the top end value.

Related