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 )
		root = createNode(item);
	else if(root->data<item)
	return root;

I wonder why the following code work.

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

	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:

root = createNode(item);

Edited 6 Years Ago by Tellalca: n/a

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.


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 ?

This question has already been answered. Start a new discussion instead.