Doing a project with BSTs, I have a logic fault somewhere in my insertion function, just can’t seem to find it.
Insertion function:
int bst_insert (bst_t *tree, bst_key_t key)
{
bst_node_t *node, *temp_node;
if( tree == NULL ) {
printf("Invalid tree pointer.\n");
return;
}
if( tree->root == NULL ) {
node = (bst_node_t *)malloc(sizeof(bst_node_t));
node->left = node->right = NULL;
node->key = key;
tree->root = node;
return 1;
}
temp_node = tree->root;
while(1) {
if( temp_node == NULL ) {
node = (bst_node_t *)malloc(sizeof(bst_node_t));
node->left = node->right = NULL;
node->key = key;
temp_node = node;
return 1;
}
if( temp_node->key == key ) {
temp_node->data_ptr = data;
return 0;
} else if( key < temp_node->key ) {
temp_node = temp_node->left;
} else if( temp_node->key < key ) {
temp_node = temp_node->right;
}
}
}
In using this function, inserting one node works just fine (probably because the tree->root is null, so it exits inside that if statement), but when I try and insert a second and leave this function, the tree only has the first node in it.
Let me know if I forgot to give any pertinent information.
The problem is here:
You’re assuming that when you perform the second assignment, it actually affects the node
temp_nodewas pointing to. But in fact, it simply replaces the contents oftemp_nodewithout changing anything else (it’s a local variable).One solution is to have a pointer to a “node pointer”. Then, when you change the value that this pointer is pointing to, you’re actually “changing the world” instead of changing a local variable. Something like:
It is possible to fix this without using a pointer-to-pointer, but then you have to keep remembering the previous (parent) pointer, and whether you need to change
leftorright.