Ugur Yilmaz
Ugur Yilmaz

Reputation: 499

C++ Binary search tree remove segmentation fault

I was trying to create a bst function for removing.However, I am struggling with this for many hours but I could not figure out what causes to segmentation fault. Can somebody help me to find out please? Here is my code;

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;

Upvotes: 1

Views: 782

Answers (1)

The Dark
The Dark

Reputation: 8514

Your removeHelper function is assigning new values to its root parameter, but those new values are lost when the function returns. As you want to change the value of the variable used to call the removeHelper function, you should pass it by reference.

bool Set::removeHelper(Node * &root, const ItemType &item) {

then the changes to the node pointer value will be reflected in the calling function.

Also note rootis a really bad name for your parameter, as it is hiding the class member variable root, which makes it very confusing to read. I would suggest changing it to something to node. e.g.:

bool Set::removeHelper(Node * &node, const ItemType &item) {

and of course, changing all the root references to node

Upvotes: 3

Related Questions