Can we use binary search tree to simulate heap operation?

后端 未结 4 748
失恋的感觉
失恋的感觉 2021-01-04 13:59

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 t

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-04 14:37

    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.

提交回复
热议问题