Pointer can not be reset to NULL within function

3

Hello everyone! I was studying binary trees and needed to create a function that would remove any nodes and their children. However, when I did this function with return / 1 / the node was not removed. Copying the return of another function from my tree, I wrote the return / 2 /, replacing the / 1 /. My question is: according to just that piece of code, is there any reason why / 1 / does not work?

Node * remover(Node *root, int valor){
if(root == NULL){
    cout<<"Elemento não encontrado."<<endl; 
}
else{
    if(root->data == valor){
        root = NULL; // isso não modifica o ponteiro? Por quê?
        cout<<"Elemento removido!"<<endl;
        return root;
    }
    if(root->data > valor){
        /* 1 */ //remover(root->left,valor); não funciona
        /* 2 */root->left = remover(root->left,valor); // funciona
        return root;
    }
    if(root->data < valor){
        /* 1 */ //remover(root->right,valor);  não funciona
        /* 2 */root->right = remover(root->right,valor); // funciona        
        return root;        
    }
}
}

Consequently, why does not this part work?:

    if(root->data == valor){
        root = NULL; // isso não modifica o ponteiro? Por quê?
        cout<<"Elemento removido!"<<endl;
        return root;
    }

Thanks for the help!

    
asked by anonymous 26.12.2015 / 03:40

1 answer

2

When you do root = NULL , you are modifying the value of the local variable root . If you want a function to receive a pointer as a parameter and modify it, you need a pointer pointer.

The signature of your function would look like this:

Node * remover(Node **root, int valor);

and the line that does not currently work would look like this:

*root = NULL;

By the way, unless you have good reason not to do so, prefer nullptr to represent lack of value. This is the null constant that provides typing security in C ++ (other than NULL , which is simply a nickname for the constant 0 ). For this, make sure you are compiling in C ++ mode 11.

    
26.12.2015 / 07:08