I have a problem root value is returning to NULL everytime I go out from the insert function I cant really understand why the pointer doesn't keep it's value.
int main(int argc, char *argv[])
{
int input;
node* root = NULL;
while (input >0 ) {
cout<< "Enter a Number:";
cin>> input;
insert (root,input);
}
printall(root);
system("PAUSE");
return 0;
}
void insert(node* _node,int val)
{
//#if 0
cout << "In insert before" << _node;
if (_node == NULL) {
_node = new node;
_node->val = val;
_node->left = NULL;
_node->right = NULL;
return;
}
//#endif
if(_node->val > val) {
insert(_node->left,val);
} else if (_node->val < val) {
insert(_node->right,val);
}
return;
}
The pointer isn't "losing" it's value. You need to pass a pointer to pointer to node to insert -- then it can "return" a pointer to node through the parameter.
You are passing root by value so it cannot be modified by the callee, you have to pass it by reference
void insert(node** _node,int val);
insert (&root,input);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With