I'm confused with code below:
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
struct node* insert(struct node* node, int data)
{
/* 1. If the tree is empty, return a new,
single node */
if (node == NULL)
return(newNode(data));
else
{
/* 2. Otherwise, recur down the tree */
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);
/* return the (unchanged) node pointer */
return node;
}
}
newNode returns a pointer to the structure it has allocated. However in line 6 of the insert function the return value of newNode is not being assigned to anything, it's just being called. How is the code further down able to use the newly created node structure?
Code below will run, if the tree is NOT empty. So, when the code in step .2 runs, the code in step .1 does not.
When the recursion unwinds, you can see that the assign operation is happening, for example:
node->left = insert(node->left, data);
Oh and as ThunderWiring said, do not cast malloc!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With