Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/objective-c/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用BinarySearchTree实现PriorityQueue:Java_Java_Binary Search Tree_Priority Queue - Fatal编程技术网

使用BinarySearchTree实现PriorityQueue:Java

使用BinarySearchTree实现PriorityQueue:Java,java,binary-search-tree,priority-queue,Java,Binary Search Tree,Priority Queue,我需要为我的算法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 – retur

我需要为我的算法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
提前感谢您的建议

A用于有效地按排序顺序维护项目。如果排序顺序基于优先级,则二叉树将成为优先级队列。您弹出最高优先级的项目,并根据其优先级插入新项目

编辑以添加:

有助于考虑替代方案——如果你使用链表作为你的队列,你如何知道在哪里插入一个新的项目,而不是通过一路遍历列表,这是O(n),使用二进制树来解决N.的最坏情况。p> 与其他数据结构相比,二进制搜索树的主要优点是相关的排序算法和搜索算法(如顺序遍历)可以非常高效

这是您的优先队列。在可能的实现中,优先级最低的项目将获得最高的数量,而优先级最高的项目将获得最低的数量。如果将这些项目插入BST,并且您按顺序读取它,那么您就有了处理队列的顺序

要处理队列,请“弹出”树中的第一个元素,其余元素将由BST自动排序

唯一需要注意的是将新元素正确插入到树中,以及删除第一个元素时会发生什么

您的方法将映射到树操作,
add
在正确的位置插入新项,并在必要时修改树,
size
例如返回树的大小,
inoorder
将遍历树


希望这能让它更清楚一点。

添加peek删除是BST的标准方法

对于搜索,您可以缓存每个节点中的大小,该大小将是该节点作为其根的子树中的当前元素数(或者换句话说
node.size=1+(node.right==null?0:node.right.size)+(node.left==null?0:node.left.size)

然后搜索就变成了

int search(E el,Node n){
    if(n==null)return -1;//stop recursion && nullpointer
    int comp = el.compareTo(n.value);
    if(comp==0)return n.left==null?0:node.left.size;
    else if(comp<0){
        return search(el,node.left);
    }else{
        int res = search(el,node.right)
        return res<0?res:res+(n.left==null?0:node.left.size)+1;//pass through -1 unmodified
    }
}
int搜索(E el,节点n){
if(n==null)返回-1;//停止递归&&nullpointer
int comp=el.比较(n.值);
如果(comp==0)返回n.left==null?0:node.left.size;

else if(comp)最左边的节点应该包含最小值的元素。当您poll()/pop()时,队列将删除该元素,并在需要时重新平衡。添加只是一个普通的添加。祝您好运,请记住,重复确实需要一些非平凡的处理。