我被要求为学校做一个项目,这是一个使用二叉搜索树的字典。 我使用我的removeWord函数有一个大问题。 我需要释放我需要删除的单词,但是当我删除根时,我无法保持指向它的指针。 这是我的代码(我只保留一个案例因为我怀疑你需要更多,所以它会更容易阅读。但如果你只是告诉我)
void removeWord(BST* tree, char* word)
{
BST* matchWord = getWord(tree, word); //point to the node matching the word to delete
if (matchWord->rightSon == NULL)
{
*tree = *(transplant(tree, matchWord, matchWord->leftSon));
}
free(matchWord); //matchWord point to the new root of the tree so iznogoud
}
BST* transplant(BST* tree, BST* first, BST* second)
{
if (first->parent == NULL)
{
tree = second; //here wordMatch becomes second as well and I don't want to
}
return tree;
}
谁能告诉我怎么做?
答案 0 :(得分:0)
找到以下可能有助于您完成项目的解决方案:
void removeWord(BST* tree, char* word)
{
//point to the node matching the word to delete
BST* matchWord = getWord(tree, word);
//If word matches then it's not NULL
if (NULL != matchWord)
{
//Find right son if NULL then
//we need to transplant left son to parent position
Transplant(tree, matchWord);
//Remove memory of removed node
free(matchWord);
matchWord = NULL;
}
}
int transplant(BST* tree, BST* matchWord)
{
if (NULL != matchWord->leftSon)
{
//Here you need to apply logic which saves matchWord's leftSon to parent's son location where matchWord is present.
//And also have to check if matchWord is having rightSon then rightSon branch is also need to be saved at right position of matchWord.
}
else if (NULL != matchWord->rightSon)
{
//Here you need to apply logic which saves matchWord's rightSon to parent's son location where matchWord is present.
//And also have to check if matchWord is having leftSon then leftSon branch is also need to be saved at left position of matchWord.
}
else
{
//Here you need to remove matchWord's location from it's parent branches.
}
}
如果有任何疑问,请告诉我。 您可能需要首先彻底了解BST,然后再对其进行操作,这对您有很大帮助。 您可以在http://en.wikipedia.org/wiki/Binary_search_tree
中找到详细信息