java - minHeap 作为二叉树
问题描述
我正在尝试将堆实现为二叉树。我需要在 O(log n) 时间内执行插入和删除功能。它只需要删除最低、最右边的节点。这是我到目前为止的 remove 函数(它是 O(n) 运行时):
public Node removeLast() {
Node k = findLastForDeletion(this.root,1, findHeightforDeletion());
if (k.parent != null && k.parent.left == k) {
k.parent.left = null;
}
else if (k.parent != null) {
k.parent.right = null;
}
return k;
}
public Node findLastForDeletion(Node n, int current, int height) {
if (current == height && n != null) {
return n;
}
else if (n == null) {
return n;
}
else {
Node k = findLastForDeletion(n.right, current + 1, height);
if (k != null) {
return k;
}
else {
return findLastForDeletion(n.left, current + 1, height);
}
}
}
public int findHeightforDeletion() {
Node l = this.root;
int lCount = 0;
while (l != null) {
l = l.left;
lCount ++;
}
return lCount;
}
我的添加功能与此相同。我只需要帮助弄清楚如何在删除之前获取最后一个节点。谢谢您的帮助!
解决方案
推荐阅读
- nativescript - Nativescript-Vue 问题与平移元素
- javascript - PostgreSQL 输出的时间戳格式与 Javascript 时间戳格式不同
- wget - wget 从网页中获取所有链接的文件
- ios - 如何在图表 ios 中设置自定义 x 轴 0 标签
- uitableview - 将行高设置为 0 swift 时,tableview 的最后一部分被打乱
- reactjs - React:提交表单后如何清除文件输入和数据输入字段?
- javascript - 如何按多个字段对值进行分组并按特定类型对其进行排序
- javascript - 模态不会关闭选择 Rails 6
- python - 我无法在 pycharm 中安装 openCV
- mysql - 如何在 MySQL 中确定合适的 max_user_connections?