Why use heap instead of binary tree when implementing priority queue?

后端 未结 5 1449
鱼传尺愫
鱼传尺愫 2021-02-15 23:31

It seems to me that the only advantage of heap over binary tree is to find the smallest item in the heap in complexity of O(1) instead of O(log(2)n) in binary tree.

When

5条回答
  •  滥情空心
    2021-02-15 23:46

    First of all there are different binary trees (some of them are quite difficult, some of them provide only average O(log n)), and heap is one of them.

    The second: while operations on most trees are O(log n), they are more complex, there is constant factor.

    Heap needs constant additional memory, while trees usually need to store pointers in every node.

    By the way, heap is quite easy and only use arrays (I'm not sure that if it's implemented this way in Java, but I do think so)

提交回复
热议问题