typedef struct nodetype
{
int data;
struct nodetype * left;
struct nodetype * right;
}node;
typedef node * tree;
tree newNode(int data)
{
tree temp;
temp = NULL;
temp = (tree)malloc(sizeof(nodetype));
temp->data = data;
temp->right = NULL;
temp->left = NULL;
return temp;
}
Here in the function newNode, to create a node we assign NULL value to the “temp”. I dont understand whether this is necessary. What will be the implications if we dont initialize it with NULL and in which cases should I take care of assigning a ptr to NULL while initializing it ??
You initialize nodes to NULL so you could differentiate empty nodes from the ones that aren’t (by checking for NULL). Otherwise you’d have no way of telling whether or not a node is empty. This is talking about the left and right nodes. There is no apparent reason why temp is initiated to NULL, you can remove that.
You assign a pointer to NULL when you don’t know if you will use it to point to something, and you will have code that checks if it has been assigned to NULL or not so it can perform some logic (like moving through a tree).