Search code examples
crecursiontreebinary-treeinsertion

Recursive Binary tree insertion


So I'm trying to insert a value into a binary tree using this recursive function:

void add(node* *hd, int v){
node* curr = *hd;
if(curr == NULL){
    curr = (node*)malloc(sizeof(node));
    curr->value = v;
}else{
    if(v < curr->value){
        add(&curr->left, v);
    }else{
        add(&curr->right, v);
    }
}
}

It doesn't seem to be working, and I just don't understand why I can't do something like this. How would I go about fixing it?


Solution

  • You need to initilize the pointers, as they probably will be set to whatever you get when allocating space. Right now when you pass add(&curr->left, v); curr->left may not be a pointer somewhere but it is still not NULL;

    void add(node* *hd, int v){
        node* curr = *hd;
        if(curr == NULL){
            curr = malloc(sizeof(node));
            curr->left = curr->right = NULL;
            curr->value = v;
            *hd = curr; // from Mohamed KALLEL
        }else{
            if(v < curr->value){
                add(&curr->left, v);
            }else{
                add(&curr->right, v);
            }
        }
    }