3
Hello, folks! I was studying binary trees and needed to create a function that would remove any knot and its children. However, when I did this function with the return /1/ the node has not been removed. Copying the return of another function from my tree, I wrote the return /2/, replacing the /1/. My question is, according to just this piece of code, is there a reason why /1/ 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 this part does not 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!
Alternatively you can also use a pointer reference (
Node *&root
).– Anthony Accioly
@Pablo, it had already crossed my mind that this would be some problem related to the fact that I n used a pointer for pointer, since I saw other trees on the internet that used this type of parameter. But since I don’t know much about pointers I wasn’t sure if that’s what it was. I will study a little more to learn how to deal with it and thank you very much for the answer and the tip on the
nullptr
, helped me a lot.– João Luca