我在从BST中删除节点时遇到了麻烦,而我似乎无法找到我的seg故障的罪魁祸首。我的BST的其他部分都经过测试,运行顺畅。我也尝试删除具有不同条件的节点,但结果完全相同。
template <typename object>
bool BST<object>::remove(object& data)
{
if (nodes == 0)
{
return false;
}
else
{
return remove(root_, data);
}
}
template <typename object>
bool BST<object>::remove(node<object>* current_node_, object& data)
{
if (current_node_ == NULL)
{
return false;
}
int relation = compare(data, current_node_->get_data());
//if you need to keep searching right
if (relation > 0)
{
remove(current_node_->get_right(), data);
}
else if (relation < 0)
{
remove(current_node_->get_left(), data);
}
else
{
//LEAF CASE
if (current_node_->is_leaf())
{
//root case
if (compare(root_->get_data(), data) == 0)
{
root_ = NULL;
}
else
{
if (current_node_->is_right_child())
{
current_node_->get_parent()->set_right(NULL);
}
else
{
current_node_->get_parent()->set_left(NULL);
}
}
//release from memory
delete current_node_;
nodes--;
}
//ONE CHILD CASE
else if (current_node_->has_one_child())
{
//root node
if (compare(root_->get_data(), data) == 0)
{
if (current_node_->get_right() != NULL)
{
current_node_->get_right()->set_parent(NULL);
root_ = current_node_->get_right();
}
else
{
current_node_->get_left()->set_parent(NULL);
root_ = current_node_->get_left();
}
}
//node with right child
else if(current_node_->get_right() != NULL)
{
current_node_->get_right()->set_parent(current_node_->get_parent());
if (current_node_->is_right_child())
{
current_node_->get_parent()->set_right(current_node_->get_right());
}
else
{
current_node_->get_parent()->set_left(current_node_->get_right());
}
}
//node with left child
else
{
current_node_->get_left()->set_parent(current_node_->get_parent());
if (current_node_->is_right_child())
{
current_node_->get_parent()->set_right(current_node_->get_left());
}
else
{
current_node_->get_parent()->set_left(current_node_->get_left());
}
}
//release from memory
delete current_node_;
nodes--;
}
//TWO CHILDREN CASE
else
{
node<object>* temp_node_ = find_min(current_node_->get_right());
object* temp_object_ = new object(temp_node_->get_data());
remove(temp_node_, temp_node_->get_data());
current_node_->set_data(*temp_object_);
}
return true;
}
return false;
}
template <typename object>
node<object>* BST<object>::find_min(node<object>* current_node_)
{
if(current_node_->get_left() != NULL)
{
find_min(current_node_->get_left());
}
else
{
return current_node_;
}
}
答案 0 :(得分:2)
写
current_node_=NULL;
每行后
delete current_node_;
删除功能。让我知道它的工作情况。