I've been trying to implement a binary search tree in C for a few hours now, and I narrowed down my main problem to the insertion function, which you see below. What appears to be the problem is that when I set root to null, and then try to insert, it creates the root node over and over but nothing changes (I get the "forming root node message" several times, traversal doesn't work). However, when I uncomment the line //root = newNode(3,NULL,NULL);, and manually create the root node, all my insertions work fine and my inorder traversal works. I'd like to be able to create the root node in my function, and not manually like this. This has been frustrating me for a while, so any help at all would be appreciated. Thanks!
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node* left;
struct node* right;
};
struct node* newNode(int val, struct node* lchild, struct node* rchild) {
struct node* temp = malloc(sizeof(struct node));
if(temp == NULL) { printf("Error creating node! Exiting."); exit(1); }
temp->key = val;
temp->left = lchild;
temp->right = rchild;
return(temp);
}
void add(int val, struct node* current) {
if (current == NULL) {
printf("forming root node\n");
current = newNode(val,NULL,NULL);
} else if (val <= current->key) {
if (current->left == NULL) {
current->left = newNode(val, NULL, NULL);
} else {
add(val, current->left);
}
} else {
if (current->right == NULL) {
current->right = newNode(val, NULL, NULL);
} else {
add(val, current->right);
}
}
}
void inOrder(struct node* current) {
if (current != NULL) {
inOrder(current->left);
printf("%d ", current->key);
inOrder(current->right);
}
}
int main() {
struct node* root = NULL;
//root = newNode(3,NULL,NULL);
add(3, root);
add(2, root);
add(4, root);
add(16, root);
inOrder(root);
}