public void delete(int pos) {
Heap[pos] = Heap[size];
size--;
int current = pos;
while (hasLeaf(current)) {
if (hasDoubleLeaf(current)
&& Heap[current] > Math.min(Heap[leftChild(current)],
Heap[rightChild(current)])) {
if (Heap[leftChild(current)] < Heap[rightChild(current)]) {
swap(leftChild(current), current);
current = leftChild(current);
} else {
swap(rightChild(current), current);
current = rightChild(current);
}
} else if (Heap[current] > Heap[leftChild(current)]) {
swap(current, leftChild(current));
current = leftChild(current);
} else{
break;
}
}
}
写了一个最小heap,这是其中删除节点函数,丑的要死,可读性太差。希望可以把代码多分支语句优化。
分支结构有两种情况,该节点有左子树或左右子树都有。
需求是和值较小的子树进行交换。
呼如林
神不在的星期二
收到一只叮咚
相关分类