Sahil
Sahil

Reputation: 69

BST insert not working

I was trying to implement a code for binary search trees. Problem is following code is not working but it works if I pass double pointer to insert funcion like insert(struct bst** node, data). I think it should also work with passing single pointers. Can anyone explain what is the error here ?

void insert(struct bst* node, int data )
{
    if (node == NULL)
    {
        printf("here with %d\n",data);
        node = (struct bst*)malloc(sizeof(struct bst));
        node->data = data;
        node->left = NULL;
        node->right = NULL;
    }
    if(data < node->data)
    {
        insert(node->left,data);
    }
    else if(data > node->data)
    {
        insert(node->right,data);
    }
}

Upvotes: 0

Views: 291

Answers (3)

xxx7xxxx
xxx7xxxx

Reputation: 824

If you want to change a pointer's value, you should pass the address of the pointer (as struct node **).

With your code:

node = (struct bst*)malloc(sizeof(struct bst));

the value of node changes in the insert function, but doesn't change the variable in the calling function.

Upvotes: 1

cxw
cxw

Reputation: 17041

You need to be able to modify the pointers in what will become the parents of node. When you make the recursive call insert(node->left,data), if node (the parent of the new node) has no left child (left==null), you are calling insert(null,data). The first if statement will then create the new node and assign its data, but there will be no way to hook that node into the tree. Also, since insert doesn't return the new node, the node is lost forever.

A quick hack to fix this would be to return the new node:

struct bst *insert(struct bst* node, int data, struct bst* parent )
{ /// Note new return value
    if (node == NULL)
    {
        printf("here with %d\n",data);
        node = (struct bst*)malloc(sizeof(struct bst));
        node->data = data;
        node->left = NULL;
        node->right = NULL;
        return node; /// NEW - send it back to the parent
    }

    if(data < node->data)
    {
        node->left = insert(node->left,data); /// save the new child if there wasn't one
        return node; /// otherwise, send back the node so the tree doesn't change.
    }
    else //if(data > node->data) /// On equal keys, add to the right
    {
        node->right = insert(node->right,data);
        return node;
    }
}

(disclaimer: code not yet tested)

Upvotes: 1

Deck
Deck

Reputation: 1979

If you want to change the value of the pointer passed to a function, you should pass it as pointer to a pointer.

void alloc_int(int** p)
{
  *p = malloc(sizeof(int));
}

int main()
{
  int* p = NULL;
  alloc_int(&p);
  *p = 10; // here memory for p is allocated so you can use it
  free(p);
  return 0;
}

The same thing in your example. You have to pass an address of pointer to change its value (value of the pointer is address of actual data).

Upvotes: 1

Related Questions