I was creating a function to insert a element in a binary tree and, first, i did the following on Visual Studio 2012:
void Insert(Nodo *root, int x){
if(root == NULL){
Nodo *n = new Nodo();
n->value = x
root = n;
return;
}
else{
if(root->value > x)
Insert(&(root)->left, x);
else
Insert(&(root)->right, x);
}
}
But this same code doesn't work at Dev-C++, I need to use Pointer of Pointer to make it work, like this:
void Insert(Nodo **root, int x){
if(*root == NULL){
Nodo *n = new Nodo();
n->value = x
*root = n;
return;
}
else{
if((*root)->value > x)
Insert(&(*root)->left, x);
else
Insert(&(*root)->right, x);
}
}
Does anybody knows why it happens?
The first code should not compile. In fact it doesn't compile under MSVC 2013.
Why ?
Your node structure should be something like this:
This means that
(root)->left
is of typeNodo*
. Hence&(root)->left
is of typeNodo**
which is incompatible with aNodo*
argument.Anyway, in your insert function, you certainly want to change the tree. But if you'd for example do:
root = n;
you would just update the root argument (pointer). This update is lost as soon as you leave the function. Here, you certainly want to change either the content of the root node or more probably the pointer to a root node.In the second version, you pass as argument the address of a pointer to a node, and then update this pointer when necessary (expected behaviour).
Remark
The first version could be "saved", if you would go for a pass by reference: