【发布时间】:2020-07-19 14:49:09
【问题描述】:
我正在尝试为我的二进制堆实现实现一个删除方法。
class Node {
constructor(priority) {
this.priority = priority;
}
}
class PriorityQueue {
constructor() {
this.heap = [null];
}
remove() {
const toRemove = this.heap[1];
this.heap[1] = this.heap.pop();
let currentIdx = 1;
let [left, right] = [2*currentIdx, 2*currentIdx + 1];
let currentChildIdx = this.heap[right] && this.heap[right].priority >= this.heap[left].priority ? right : left; //Assess which child node has higher priority
while (this.heap[currentChildIdx] && this.heap[currentIdx].priority <= this.heap[currentChildIdx].priority) {
let currentNode = this.heap[currentIdx]
let currentChildNode = this.heap[currentChildIdx];
this.heap[currentChildIdx] = currentNode;
this.heap[currentIdx] = currentChildNode;
currentIdx = this.heap.indexOf(currentNode);
}
return toRemove;
}
}
但是,我不确定在运行 while 循环时如何正确更新 currentIdx 和 currentChildIdx 的值。事实上,当我尝试更新 currentIdx 的值时,代码似乎停止工作
currentIdx = this.heap.indexOf(currentNode);
关于我做错了什么的任何提示?
【问题讨论】:
标签: data-structures priority-queue binary-heap