1
我試圖創建一個bst函數進行刪除。但是,我掙扎了很多小時,但我無法弄清楚是什麼導致了段錯誤。有人能幫我找出答案嗎?這是我的代碼;C++二進制搜索樹刪除段錯誤
bool Set::remove(const ItemType & item) {
return removeHelper(root, item);
}
bool Set::removeHelper(Node *root, const ItemType &item) {
if (root == NULL) {//check if root is null
return false;
}
else if (item == root->data) {//check if item equals to root
Node *temp = root;
if (root->right == NULL && root->left == NULL) {//check if roots equal to null
root = NULL;
}
else if (root->right == NULL) {//check if root equals to null
root = root->left;
}
else if (root->left == NULL) {//check if root equals to null
root = root->right;
}
else {
Node *p = root; //it is like parent root
temp = temp->right;
while (temp->left != NULL) {//check if temp root equals to null
p = temp;
temp = p->left;
}
if (p == root) {//check if root equals to parent
p->right = temp->right;
}
else {
p->left = temp->right;
}
root->data = temp->data;
}
delete temp;//delete temp node
return true;
}
else if (item < root->data)
removeHelper(root->left, item);//call recursive delete function
else if (item > root->data)
removeHelper(root->right, item);//call recursive delete function
return false;
你好,是的,它是。我編輯過。謝謝! –