The built-in iterator for java's PriorityQueue does not traverse the data structure in any particular order. Why?

后端 未结 5 1022
说谎
说谎 2020-11-22 08:43

This is straight from the Java Docs:

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

5条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 09:34

    Binary heaps are an efficient way of implementing priority queues. The only guarantee about order that a heap makes is that the item at the top has the highest priority (maybe it is the "biggest" or "smallest" according to some order). A heap is a binary tree that has the properties: Shape property: the tree fills up from top to bottom left to right Order prperty: the element at any node is bigger (or smaller if smallest has highest priority) than its two children nodes. When the iterator visits all the elements it probably does so in a level-order traversal, i.e. it visits each node in each level in turn before going on to the next level. Since the only guarantee about order that is made that a node has a higher priority than its children, the nodes in each level will be in no particular order.

提交回复
热议问题