简体   繁体   中英

Access Violation Exception in Visual Studio in Deletion of node in Binary Search Tree

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?

Assuming you have a member variable named root , then the problem probably is because you shadow the member variable root with the argument root in your deletion function. So when you do root = NULL in the function, you only set the argument to NULL and not the member variable.

There is also the problem with the other assignments to root , which will just assign to the local argument and not the member variable as well.

The fix you've made (assigning to root in the calling function) is, I think, the most correct solution.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM