[英]Does not remove last item in Boolean remove(object o) method
这删除了几乎所有应该删除的内容,除了最后一项。 这是我提交时得到的:
输入:[东西,单词,东西,和,动物园,是的]
----------预期大小:0 BST 实际节点数:1
删除事物后无效的树
代码如下:
@SuppressWarnings("unchecked")
public boolean remove(Object o) {
Node n = root;
while (n != null) {
int comp = n.value.compareTo(o);
if (comp == 0) {
size--;
remove(n);
return true;
} else if (comp > 0) {
n = n.left;
} else {
n = n.right;
}
}
return false;
}
private void remove(Node root) {
if (root.left == null && root.right == null) {
if (root.parent == null) {
root = null;
} else {
if (root.parent.left == root) {
root.parent.left = null;
} else {
root.parent.right = null;
}
}
} else if (root.left == null || root.right == null) {
Node child = root.left;
if (root.left == null) {
child = root.right;
}
if (root.parent == null) {
root = child;
} else if (root.parent.left == root) {
root.parent.left = child;
} else {
root.parent.right = child;
}
child.parent = root.parent;
} else {
Node successor = root.right;
if (successor.left == null) {
root.value = successor.value;
root.right = successor.right;
if (successor.right != null) {
successor.right.parent = root;
}
} else {
while (successor.left != null) {
successor = successor.left;
}
root.value = successor.value;
successor.parent.left = successor.right;
if (successor.right != null) {
successor.right.parent = successor.parent;
}
}
}
}
删除二叉搜索树中的节点包括以下步骤:
您需要确保您有一个用于搜索的函数,以便找到要删除的节点。
如果节点的子节点少于两个,则可以轻松更改子树。 如果有子节点,则当前节点将被其子节点替换。 否则,如果要删除的节点有两个子节点,则只需将要删除的节点替换为左子树的最右侧节点或要删除的元素的右子树的最左侧节点即可。
为了实现这一点,您将需要以下方法: - 搜索 - 找到子树最左边/最右边的节点 - 删除
您当前的代码过于复杂。 我会使用原子方法重写它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.