我需要为算法II类“创建由二叉搜索树(BST)实现的优先级队列”。但是,我不确定您将如何使用二进制搜索树作为优先级队列。有人可以说明任务要我做什么吗?
作为引用,以下是PriorityQueue必须实现的方法:
add – adds a new item to the queue
peek – returns the head of the queue
remove – removes the head of the queue and returns it
search – returns the position of an element in the queue, or -1 if it is not found.
size – returns the total number of elements in the queue
inorder – returns an in-order, comma-separated string of every element in the queue
preorder – returns an pre-order, comma-separated string of every element in the queue
height – returns the height of the underlying BST
预先感谢您的任何建议!
最佳答案
Binary Search Tree始终是有序的,如果插入了新项目,它将始终保持顺序。
这就是您的优先队列。在可能的实现中,优先级最低的项目将获得最高数量,而优先级最高的项目将获得最低数量。如果将这些项目插入到BST中,并且您将其读取为inorder
,那么您具有处理队列的顺序。
要处理队列,请“弹出”树中的第一个元素,其余元素将由BST自动排序。
您唯一需要注意的是将新元素正确插入树中,如果删除了第一个元素,会发生什么情况。
您的方法将映射到树操作,add
在正确的位置插入一个新项,并在必要时修改树,例如size
返回树的大小,inorder
将遍历树。
希望这使它更加清晰。
关于java - 使用BinarySearchTree : Java实现PriorityQueue,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6084676/