A Way For Learning

What's the difference between a binary search tree and a binary heap?

No comments

Heap just guarantees that elements on higher levels are greater (for max-heap) or smaller (for min-heap) than elements on lower levels, whereas BST guarantees order (from "left" to "right"). If you want sorted elements, go with BST.


 Heap is better at findMin/findMax (O(1)), while BST is good at all finds (O(logN)). Insert is O(logN) for both structures. If you only care about findMin/findMax (e.g. priority-related), go with heap. If you want everything sorted, go with BST.

Advantages of binary heap over a balanced BST
Advantage of BST over binary heap
  • search for arbitrary elements O(log(n))O(n) for heap, in which the only fast search is for the largest element O(1). This is the killer feature of BSTs.
"False" advantage of heap over BST
Average binary heap insert is O(1)

No comments :

Post a Comment