I have a Binary Search Tree that I’m making and I implemented the Insert node code as follows:
BSTNode * BST::Insert(const std::string & v){
BSTNode * node = new BSTNode(v);
if (root == NULL){
root = node;
} else if (root->value.compare(v) > 0) {
Insert(root->left, node);
//recursive insert the method
} else if (root->value.compare(v) < 0) {
Insert(root->right, node);
} else {
delete node;
return NULL;
}
size++;
return node;
}
Followed by the recursive insert method in my header file (it has private access):
void Insert(BSTNode* current, BSTNode* node){
if (current == NULL){
current = node;
} else if (current->value == node->value){
delete node;
} else if (current->value < node->value) {
Insert(current->left, node);
} else if (current->value > node->value){//if (parent->value < node->value) {
Insert(current->right, node);
}
}
When the recursive function sets the pointer and then returns, the changes I made to the pointer DON’T stay.
The problem here is that
currentis a local variable with a copy of the value of the pointer. It’s not the same variable that you pass in. If you want to modify the pointer in place, your method should accept either a pointer to the pointer or a reference to the pointer. The easiest way to do this would be to just modifycurrentto be a reference to a pointer. The resultant code would look like this:In general, you should keep in mind that pointers are just values which tell you the memory location of something. So they’re really just numbers. And when they’re passed into a function, unless there’s a reference, they’re passed by the value. So your function just sees the number, not the variable which contained the number.