Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we use binary search tree to simulate heap operation?

I was wondering if we can use a binary search tree to simulate heap operations (insert, find minimum, delete minimum), i.e., use a BST for doing the same job?

Are there any kind of benefits for doing so?

like image 339
Junaid Avatar asked Oct 24 '11 16:10

Junaid


2 Answers

Sure we can. but with a balanced BST.

The minimum is the leftest element. The maximum is the rightest element. finding those elements is O(logn) each, and can be cached on each insert/delete, after the data structure was modified [note there is room for optimizations here, but this naive approach also doesn't contradict complexity requirement!]

This way you get insert,delete: O(logn), findMin/findMax: O(1)

EDIT:
The only advantage I can think of in this implementtion is that you get both findMin,findMax in one data structure.
However, this solution will be much slower [more ops per step, more cache misses are expected...] and consume more space then the regular array-based implementation of a heap.

like image 123
amit Avatar answered Oct 18 '22 04:10

amit


Yes, but you lose the O(1) average insert of the heap

As others mentioned, you can use a BST to simulate a heap.

However this has one major downside: you lose the O(1) insert average time, which is basically the only reason to use the heap in the first place: https://stackoverflow.com/a/29548834/895245

If you want to track both min and max on a heap, I recommend that you do it with two heaps instead of a BST to keep the O(1) insert advantage.