[英]BST delete method doesn't delete the first node inserted
I can't figure this out... I can insert and sort items with no issue, I can delete nodes past the first insert, but on the special case that I'm trying to delete the first node inserted to start the tree, it doesn't do anything. 我无法弄清楚...我可以毫无问题地插入和排序项目,可以删除第一个插入之后的节点,但是在特殊情况下,我试图删除插入的第一个节点以启动树,它什么也没做。
I'm not understanding why this issue is happening, any help to figure out the logic is appreciated. 我不明白为什么会发生此问题,感谢您对找出逻辑的任何帮助。
Watered down version of my code the replicates the problem. 淡化我的代码版本可以解决问题。 https://pastebin.com/hxcqpG1U
https://pastebin.com/hxcqpG1U
Here is my delete method: 这是我的删除方法:
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;
}
Assuming your tree does no balancing, the first node inserted will be the root node of the tree. 假设树没有平衡,则插入的第一个节点将是树的根节点。 Since your delete method operates by updating the in-tree references to point around the deleted node, trying to delete the root node won't do anything unless you also update the pointer to the root node.
由于您的delete方法通过更新树内引用以指向已删除节点周围来进行操作,因此尝试删除根节点不会做任何事情,除非您还更新了指向根节点的指针。
It's hard to tell from the code you've provided, but it seems likely that you need something like: 从提供的代码中很难看出来,但似乎您需要类似以下内容:
public void delete(KeyComp key) {
_root = delete(_root, key);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.