![](/img/trans.png)
[英]Delete node function will not delete certain nodes from a binary search tree
[英]Trying to delete a node from a binary search tree
刪除節點后嘗試顯示樹時出現內存錯誤。
這是我的刪除(刪除)方法:
void binarySearchTree::remove(int x, node * r)
{
bool found = false;
node * previous = NULL;
if (root == NULL)
{cout << "Tree is empty. Nothing to remove." << endl; return;}
while (!found)
{
if (x < r->data)
{
previous = r;
r = r->left;
}
else if (x > r->data)
{
previous = r;
r = r->right;
}
else
found = true;
}
if (r->left == NULL && r->right == NULL) //case 1: node to be deleted is a leaf (no children)
{
delete r;
return;
}
else if(r->left == NULL && r->right != NULL) //case 2: node only has a right child
previous->right = r->right;
else if (r->left != NULL && r->right == NULL) //case 2: node only has a left child
previous->left = r->left;
else
{ //case 3: node has two children
node * minNode = findMinNode(r->right); //finds min node in the right sub tree
r->data = minNode->data;
delete minNode;
return;
}
delete r;
}
我的findMinNode方法:
binarySearchTree::node * & binarySearchTree::findMinNode(node * r)
{
if (r == NULL) //if tree is empty
return r;
if (r->left == NULL && r->right == NULL)
return r;
else if (r->left != NULL)
return findMinNode(r->left);
else
return findMinNode(r->right);
}
我的顯示方法(使用預遍歷):
void binarySearchTree::display(node * r)
{
if (r == NULL)
return;
display(r->left);
cout << r->data << endl;
display(r->right);
}
我正在使用公共display()
方法,然后調用此私有display(node * r)
方法。
我知道問題出在我使用delete
因為當我單步執行代碼並進入display()
方法時,當它檢查我剛剛刪除的節點上是否r== NULL
時,該地址不是NULL
為0x000000000
但具有0x000000001
。 因此,我的程序將崩潰。 我以前從未遇到過這個問題。 任何幫助將不勝感激。
我應該補充一點,我按以下確切順序插入了這些值:10、5、34、2、8、12、25、6、18、27、38、11。我試圖刪除值為12的節點,因為它具有兩個孩子。
刪除節點時,您需要使指向該節點的指針為NULL,在您的示例中,該指針可以是root,previous-> left或previous-> right。 如果將上一個更改為node **
並將其指向上一個指針(初始化為&root),則可以說*previous = null
或*previous = r->right
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.