I am trying to add a node to a binary search tree (BST). My adding method code is as follows:
int add(node_t* n, node_t* tn){
if(tn == NULL){tn = n;}
if(n->value < tn->value){add(n, tn->leftNode);}
else if (n->value > tn->value){add(n, tn->rightNode);}
else{return 0;}
return 1;
}
The method is called in main for BST t1
and node n1
: add(n1, t1->root)
. The return value of the function is a 0
or 1
, 0
if another node of the same value exists in the tree- in which case the new node is not added- and 1
if the node is successfully added. Struct tree_t
's count variable is updated in the main function as follows: t1->count += add(n1, t1->root)
.
However, after I call the add
function, the tree t1
still seems to be empty. My only guess is that add
is adding a node to a copy of t1
which is being destroyed after the function call, but I don't understand why this is the case as it is passed in as a pointer.
The structs tree_t
and node_t
are attached below:
typedef struct node{
int value;
struct node* leftNode;
struct node* rightNode;
} node_t;
typedef struct tree{
struct node* root;
int count;
} tree_t;
And here is my main method:
int main(){
tree_t t1;
tree_init(&t1);
node_t n1;
node_init(&n1, 5);
node_t n2;
node_init(&n2, 7);
t1.count += add(&n1, t1.root);
t1.count += add(&n2, t1.root);
print_tree(t1.root); //this prints nothing, and I'm confident that print_tree works
}
Any help is greatly appreciated!