0

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;
}
3
Contributors
5
Replies
7
Views
6 Years
Discussion Span
Last Post by Tellalca
Featured Replies
  • 1
    Narue 5,707   6 Years Ago

    [QUOTE]I wonder why the following code work.[/QUOTE] It doesn't. The recursive calls fail to fix the subtree: [code] if(root->data>item) root->left = insert(root->left,item); else if(root->data<item) root->right = insert(root->right,item); [/code] Read More

  • 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 ? Read More

1

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);
0

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);

Edited by Tellalca: n/a

0

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.

1

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.