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:
temp_node = tree->root;
...
temp_node = node;
You're assuming that when you perform the second assignment, it actually affects the node temp_node
was pointing to. But in fact, it simply replaces the contents of temp_node
without 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:
bst_node_t **temp_node;
...
temp_node = &tree->root;
/* To change the value that temp_node is pointing to */
*temp_node = node;
/* To change temp_node itself */
...
} else if( key < temp_node->key ) {
temp_node = &temp_node->left;
} else if( temp_node->key < key ) {
temp_node = &temp_node->right;
}
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 left
or right
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.