As Griff already pointed out there are a couple of things totally wrong in your code, and you can see them by just looking at it. Let's start with your main program:
node *root=(node*)malloc(sizeof(node));
root=NULL;
insert(root,4);
Obviously, you meant to allocate a root node in the first line, but then just for testing purposes reset root to NULL again, in which case the memory you just have allocated would be lost -- a memory leak. Now you have to decide whether you want the user of your
insert
function to always allocate the root node by himself, or whether you want to start with a root pointer that is NULL. I'd go for the second option. So throw that malloc line out.
So, we have decided that in the very first call the
insert
function is going to allocate the root node for us. But how can it return that pointer? In the declaration
void insert(node *root,int item)
you specified root as a pointer that is transferred by value. That doesn't give us a chance to return a value back to our caller. To remedy that we have to pass the root pointer via a pointer to a pointer:
void insert (node** ppRoot, int item)
And now we can allocate a root node inside the insert function:
void insert (node** ppRoot, int item)
{
node* pRoot = *ppRoot;
if (pRoot == NULL)
{
*ppRoot = pRoot = (node*) malloc (sizeof (node));
pRoot->item = item;
pRoot->left = NULL;
pRoot->right = NULL;
}
In your main function you would now call
insert
the following way:
root = NULL;
insert (&root, 4);
And there is one other thing that I would change: The parent pointer in your insert function points to the node to which you have to link your newly allocated node. The problem is just that you don't know whether to link it to the
left
or
right
pointer of the parent node. You solved that by comparing the item once again to the parent's value. A more elegant way is to use a pointer that point to the location into which the link has to be placed, i.e. (
left
or
right
).
node** ppLink;
...
while (cur != NULL)
{
if (item <= cur->info)
ppLink = &cur->left;
else
ppLink = &cur->right;
cur = *ppLink;
}
...
{
node* pNewNode = (node*) malloc (sizeof(node));
*ppLink = pNewNode;
...
Got it?
As you see, the concept of pointers to pointers is very powerful. The above explanations were just meant to get you going into the right direction. They don't fix all the problems in your code. In any case: Learn how to use the debugger. That will become your most important tool as a programmer!
Good luck.