I have a binary tree program, when I am trying to traverse the tree for insertion in a recursive function pointer assignment does not seem to work. First things first here is the inserting function which is not working:
void append(Node* &curr, int val){
if(curr==nullptr){
Node* newNode = new Node(val);
std::cout << "Created new Node with value: " << newNode->value << std::endl;
curr = newNode;
return;
}
if(curr->value > val){
curr = curr->left;
append(curr, val);
}
else{
curr = curr->right;
append(curr,val);
}
}
But when I tweak the same function like following, it seems to work just fine:
void append(Node* &curr, int val){
if(curr==nullptr){
Node* newNode = new Node(val);
std::cout << "Created new Node with value: " << newNode->value << std::endl;
curr = newNode;
return;
}
if(curr->value > val){
append(curr->left, val);
}
else{
std::cout << "Right" << curr->value << std::endl;
append(curr->right,val);
}
}
I came to fix this after hours of work, and still can't understand why the first function does not work while the second one works as expected. Was hoping anyone can tell me why curr=curr->left is different than passing curr->left to the recursion.