所以我正在编写BST节点删除功能,但我无法找出问题:
我有这个节点数据结构:
struct webentry
{
char * topic;
char * keyword;
char * url;
char * summary;
char * review;
int rating;
};
问题发生在节点有两个子节点且其右子节点有一个左子节点的位置(意味着我需要找到inorder后继节点并替换它):
else if ((root->right != NULL) && (root->left !=NULL) && (root->right->left !=NULL))
{
node*tempr = root->right;
node*templ = root->left;
delete root->data.topic;
delete root->data.keyword;
delete root->data.url;
delete root->data.summary;
delete root->data.review;
delete root;
root = findis(tempr);
root->right = tempr;
root->left = templ;
return 1;
}
我写了一个findis
函数来处理inorder后继情况:
node* program4::findis(node* &root)
{
/* cout to figure out what's going on
cout<<"Topic: "<<root->data.topic<<endl; Finds it here
cout<<"Keyword: "<<root->data.keyword<<endl; Finds it here
*/
if ((root->left==NULL) && (root->right ==NULL))
{
node*temp = root;
delete root;
root = NULL;
/*
cout<<"Topic: "<<temp->data.topic<<endl; Empty
cout<<"Keyword: "<<temp->data.keyword<<endl; Finds
*/
return temp;
}
else if ((root->left == NULL) && (root->right != NULL))
{
node*temp= root;
node*tempn = root->right;
delete root;
root = tempn;
/*
cout<<"Topic: "<<root->data.topic<<endl;
cout<<"Keyword: "<<root->data.keyword<<endl;
*/
return temp;
}
else
{
return findis(root->left);
}
问题是:当节点inorder后继返回时,topic
部分变为NULL
,其他所有内容都保持不变。我已经使用GDB来确定它删除主题内容的位置,它正好在我if
条件满足后标记的位置,并删除了findis
函数中的根。它不会删除该节点的任何其他数据,我也不知道为什么它甚至删除它。谁能看到这里发生了什么?