Hello :)
I have to write a C-code for a binary search tree.
It will read from a textfile and create with it a tree. When I execute the file I should have all data from the file in the tree and it should print the numbers in order. I should probably mention that this is a phone book so there is not only a number but also a name.
So far, my program only prints three numbers, without the name. I tried several solutions and debugs and realized that the issue is in the insert function. I cannot change the function, which is a given void function, and therefore I can't use recursion. The three numbers are inorder though!
If there is a number twice, the program is supposed to return but I tried a lot of places and can't find where I should put this condition.
Also, according to my printf-debugging my program reads everything from the textfile but doesn't print it.
I have been sitting on it for a whole week, always spending several hours on the computer in front of my code. It would be awesome if someone could help me here :)
I would rather have someone point mistakes out instead of just sending me back my whole code that is already adjusted because I really want to understand what doesn't work :)
Code:
void bst_insert_node(bstree* bst, unsigned long phone, char *name)
{
bst_node* node = malloc(sizeof(bst_node));
node->phone = phone;
node->name = name;
node->parent = NULL;
node->left = NULL;
node->right = NULL;
bst_node* tmp = malloc(sizeof(bst_node));
tmp->phone = phone;
tmp->name = name;
tmp->parent = NULL;
tmp->left = NULL;
tmp->right = NULL;
while (tmp != NULL)
{
node->parent = tmp;
if(node->phone < tmp->phone)
{
tmp = tmp->left;
}
else
{
tmp = tmp->right;
}
}
node->parent = bst->root;
if(node->parent == NULL)
{
bst->root = node;
}
else
{
if(node->phone < node->parent->phone)
{
node->parent->left = node;
}
else
{
node->parent->right = node;
}
bst->count++;
}
}