I wonder why the following code work. In the debugger i see that every thing works fine but after the "root = createNode(item);" statement I can't see the new node assigned to root?

Node *insert( Node *root, int item )
{
	if(root==NULL)
		root = createNode(item);
	if(root->data>item)
		insert(root->left,item);
	else if(root->data<item)
		insert(root->right,item);
	return root;
}

I wonder why the following code work.

It doesn't. The recursive calls fail to fix the subtree:

if(root->data>item)
	root->left = insert(root->left,item);
else if(root->data<item)
	root->right = insert(root->right,item);

Oh you are right, i meant why does not the code work. But i dont seem to get why the code needs extra assignment like "root->left = insert(root->left,item);" .

It seems ok to me if i assign the newly created node to the root with:

if(root==NULL)
root = createNode(item);

I got something. As we insert the leaf to for example root->left, we insert the new node but root still does not know the adress hence the pointer is still NULL. Is this the problem with my code?


As you said if we do it that way: "root->left = insert(root->left,item);" root now knows the adress of the new node. Am i right ? I am new to recursion and it seems a little complicated at first.

Thanks.

Yes I think you are correct. But I advise you to cement your understanding by using some example.
For instance if I have the data 10,20,15, how will the code handle it ?

Thank you both. I got it now. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.