I tried to implement a binary search tree for the purpose of (re-)learning C. The problem is that the this current = new; does not work as desired because the tree.root is still a null pointer after adding two nodes. What's wrong with that?
#include <stdlib.h>
#include <stdio.h>
typedef struct BinaryNode {
int key;
double value;
struct BinaryNode *left;
struct BinaryNode *right;
} BinaryNode;
typedef struct BinaryTree {
struct BinaryNode *root;
} BinaryTree;
static void binary_tree_insert_recursive(BinaryNode *current, BinaryNode *new) {
if (current == NULL || current->key == new->key) {
current = new;
} else if (current->key > new->key) {
binary_tree_insert_recursive(current->left, new);
} else if (current->key < new->key) {
binary_tree_insert_recursive(current->right, new);
}
}
void binary_tree_insert(BinaryTree *tree, int key, double value) {
BinaryNode *new = (BinaryNode *) malloc(sizeof(BinaryNode));
new->key = key;
new->value = value;
binary_tree_insert_recursive(tree->root, new);
}
int main(void) {
BinaryTree tree;
binary_tree_insert(&tree, 5, 123);
binary_tree_insert(&tree, 10, 123);
printf("%p\n", tree.root);
return 0;
}
Thank you!