开发者

about heap(max-heap and min heap)

I have this question that in the heap data structure , a left child can be more than a right child in its own level ? I mean that consider these three numbers 9,5,8 and I want to make a max-heap data 开发者_如何学Pythonstructure so the root will be 9 and is it true that 8 be its left child and 5 be its right child? please help me thanks


Max-Heap properties:

  1. Root is the max element. O(1) time to search for max element.
  2. Children is always smaller than root of any sub-tree.(there is no conditions between left and right children)
  3. Minimum element lies somewhere in the leaf elements, i.e. O(n/2) == O(n) time is needed to find the minimum element.

Min-Heap properties:

  1. Root is the min element. O(1) time to search for mim element.
  2. Children is always greater than root of any sub-tree.(there is no conditions between left and right children)
  3. Maximum element lies somewhere in the leaf elements, i.e. O(n/2) == O(n) time is needed to find the maximum element.

Hence, Heap is not suitable for searching but it is used for sorting an array of elements, because searching takes linear O(n) time.

For searching, we could always go for Binary Search trees(BSTs) which does the same thing in O(h) time. And in best case, it would do the searching in O(logn) if the BS tree is balanced.


That doesn't matter. A node in a max-heap must have children that are lower, and a node in a min-heap must have children that are greater. Those are the only requirements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜