-1

I'm implementing my own binary tree and this is my node structure:

struct node {
    int value;
    struct node *left;
    struct node *right;
};

and my start node:

struct node * start = NULL;

this is my insert function:

void insert(int value, struct node *leaf) {
    if (leaf == NULL) {
        leaf = (struct node*) malloc( sizeof( struct node ) );
        leaf->value = value;
        leaf->left = NULL;    
        leaf->right = NULL;  
    } else if (value < leaf->value) {
        insert(value, leaf->left);
    } else if (value > leaf->value) {
        insert(value, leaf->right);
    }
}

and this is the function I use for visiting the tree:

void print_tree(struct node * leaf) {
    if (leaf == NULL)
        return;
    print_tree(leaf->left);
    printf(" %d ", leaf->value);
    print_tree(leaf->right);
}

The problem is that after I insert all the values it prints nothing.

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31
f.saint
  • 33
  • 2
  • 6

1 Answers1

1

I'm assuming that you're calling the insert in this way:

insert(5, start);

The problem is that in this way you are copying NULL into the leaf local variable of the insert function.

So also if you are allocating memory for the nodes, you aren't updating the start pointer.

In order to do this you need to use a double pointer in your insert function (struct node ** leaf).

This should work:

void insert(int value, struct node **leaf)
{
    if( (*leaf) == NULL )
    {
        (*leaf) = malloc( sizeof( struct node ) ); // You don't need casting
        (*leaf)->value = value;
        (*leaf)->left = NULL;    
        (*leaf)->right = NULL;  
    }
    else if(value < (*leaf)->value)
    {
        insert( value, &(*leaf)->left );
    }
    else if(value > (*leaf)->value)
    {
        insert( value, &(*leaf)->right );
    }
}
granmirupa
  • 2,780
  • 16
  • 27