I am getting Exception when running the BST Deletion. Below is my code snippet:
Bst::node * Bst::del(node *root, int num)
{
if (root == NULL)
{
return root;
}
else if (num < root->data)
{
root->left = del(root->left, num);
}
else if (num > root->data)
{
root->right = del(root->right, num);
}
else
{
if (root->left == NULL)
{
node * tmp = root;
root = root->right;
delete tmp;
}
else if (root->right == NULL)
{
node * tmp = root;
root = root->left;
delete tmp;
}
else if (root->left == NULL && root->right == NULL)
{
delete root;
root = NULL;
}
else
{
node *tmp = root;
tmp = findMin(root->right);
root->data = tmp->data;
root->right = del(root->right, tmp->data);
}
}
return root;
}
void Bst::del(int num)
{
del(root, num);
}
Everything works fine when I am deleting the other nodes but when I delete the root node itself then the function void Bst::del(int num)
gets the garbage value from the function Bst::node * Bst::del(node *root, int num)
. The error gets resolved when I rewrite my function as
void Bst::del(int num)
{
root = del(root, num);
}
Question 1. Why it works when I delete the middle nodes or any other node except the root node. While debugging I found that even root was getting deleted properly when the function Bst::node * Bst::del(node *root, int num)
was executing but when the call returned to the void Bst::del(int num)
then the value of root was not getting retained and was garbage.
Question 2: Why the error got fixed when I stored the returned value in variable root
?
While deleting a BST node using recursion, you must track the root node, which you're doing correctly as
root->left = // ...
and root->right = ...
However when call reaches to caller after unwinding the stack, the root may get modified ( case when you delete the root itself )
This hopefully answers both of your questions
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.