【发布时间】:2018-10-04 10:18:36
【问题描述】:
我创建了一个Binary Search Tree 并尝试在添加特定节点后删除它们。我可以成功 delete 大约 5 Nodes 但是当我尝试删除 Node with id 109 它只是忽略它并且没有任何反应。我试过很多方法来删除它,但它不起作用。
myBinaryTree.deleteNode(myBinaryTree.root, 109);
这是我的二叉树中的delete 方法。
public Node deleteNode(Node root, int ID){
if (root == null) return root;
if (ID < root.ID)
root.leftChild = deleteNode(root.leftChild, ID);
else if (ID > root.ID)
root.rightChild = deleteNode(root.rightChild, ID);
else
{
if (root.leftChild == null)
return root.rightChild;
else if (root.rightChild == null)
return root.leftChild;
root.ID = minValue(root.rightChild);
root.rightChild = deleteNode(root.rightChild, root.ID);
}
return root;
}
int minValue(Node root)
{
int minv = root.ID;
while (root.leftChild != null)
{
minv = root.leftChild.ID;
root = root.leftChild;
}
return minv;
}
还有我的Node:
public class Node {
int ID;
Dancer.Gender gender;
int height;
Node leftChild;
Node rightChild;
Node(int ID, Dancer.Gender gender, int height) {
this.ID = ID;
this.gender = gender;
this.height = ID;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
}
ID 按预期工作意味着deleteNode 方法获得了正确的 ID,它只是不删除它。
这是我要从中删除的一棵树的图片:
如果需要有关如何添加节点等的更多信息,那么我也可以提供。在我尝试使用ID = 109 删除节点之前,这一切都很奇怪。
【问题讨论】:
-
你调试过吗?我会怀疑
ID > root.ID不是真的,或者不会出现在右侧。 -
你可能需要稍后修复的东西:
this.height = ID;它来自 Node 构造函数。 -
@achAmháin 它最终在
else if (root.rightChild == null) return root.leftChild -
@dbl 目前是打算的,但以后会做
-
这意味着它错误地超过了
else if (ID > root.ID)。您能否提供您传递给deleteNode的Node代码?
标签: java binary-search-tree nodes