0

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!

rjc810
  • 425
  • 1
  • 3
  • 17

1 Answers1

0

If you pass to function pointer to type, you can change the variable that pointer points to. But you can't change the address, that this pointer points to (can't change pointer itself). If you want to change pointer itself (address that he points to), you need to pass in your function pointer to pointer:

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;
}
Igor_M
  • 308
  • 2
  • 12