每当我插入树数据并尝试删除它时,它都适用于除最后剩余节点之外的所有数据。或者即使我只插入一个节点并尝试删除它,它也不会,它会继续显示节点。我尝试调试代码,但似乎无能为力。请帮忙!
void Remove(node *Current, int key) {
node *prev = new node;
if(Current == NULL)
cout << "List is empty.\n";
else {
while(Current != NULL) {
if(Current->value == key)
break;
else {
prev = Current;
if(Current->value >key)
Current = Current->left;
else
Current = Current->right;
}
}
if(Current->left == NULL && Current->right == NULL) {
if(prev->left == Current)
prev->left = NULL;
else
prev->right = NULL;
delete(Current);
}
else if(Current->left != NULL && Current->right == NULL) {
if(prev->left == Current)
prev->left = Current->left;
else
prev->right = Current->left;
delete(Current);
}
else if(Current->left == NULL && Current->right != NULL) {
if(prev->left == Current)
prev->left = Current->right;
else
prev->right = Current->right;
delete(Current);
}
else if(Current->left != NULL && Current->right != NULL) {
node *temp = Current->right;
if(temp->left == NULL && temp->right == NULL) {
Current->value = temp->value;
delete(temp);
Current->right = NULL;
}
//////////////////////////////////////
else if(Current->right->left != NULL)
{
node *left_current = Current->right;
node *left_current_prev = Current->right->left;
while(left_current->left != NULL)
{
left_current_prev = left_current;
left_current = left_current->left;
}
Current->value = left_current->value;
delete(left_current);
left_current_prev->left = NULL;
}
//////////////////////////////////////
else
{
node *temp;
temp = Current->right;
Current->value = temp->value;
Current->right = temp->right;
delete(temp);
}
//////////////////////////////////////
}
}
}
答案 0 :(得分:0)
如果我只插入一个节点并尝试删除它,则不会 继续显示节点
每棵树都有一个基础,一个指向树的第一个节点的指针。
tree base --> Current node --> left node ...
--> right node ,,,
此基本指针似乎对函数Remove,
的调用者可用 ... code leading to
Remove (tree base->Current, key)
... subsequent code
但您没有授予对树库的删除访问权限以进行修改。
换句话说,Remove()(可能)删除Current,但是tree base仍然指向Remove()返回时Current的位置。
您可能需要查看当密钥与最后一个节点中的值不匹配时会发生什么。