Recursive Binary tree insertion

Man Person picture Man Person · Nov 28, 2012 · Viewed 9.7k times · Source

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?

Answer

1-----1 picture 1-----1 · Nov 28, 2012

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);
        }
    }
}