【发布时间】:2018-10-11 17:29:43
【问题描述】:
我想不通...我可以毫无问题地插入和排序项目,我可以删除第一个插入之后的节点,但在特殊情况下,我试图删除插入的第一个节点以启动树,它什么也没做。
我不明白为什么会发生这个问题,感谢任何帮助找出逻辑的帮助。
我的代码的淡化版本复制了问题。 https://pastebin.com/hxcqpG1U
这是我的删除方法:
public void delete(KeyComp key) {
delete(_root, key);
}
private Node delete(Node root, KeyComp key) {
//TO-DO: DELETE AN ITEM IN THE TABLE, GIVEN THE KEY
//empty tree
if (root == null)
return root;
if (key.keyCompareTo(root.data) < 0)
root.left = delete(root.left, key);
else if (key.keyCompareTo(root.data) > 0)
root.right = delete(root.right, key);
else
{
// node with only one child or no child
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
// node with two children: Get the inorder successor (smallest
// in the right subtree)
root.data = getMin(root.right).data;
// Delete the inorder successor
root.right = delete(root.right, root.data);
}
return root;
}
【问题讨论】:
标签: java search tree binary binary-search-tree