Reputation: 67
There is some my code. I have a problem.
int insert2( int num, binarytree** root)
{
if ( *root == NULL )
{
*root = setnode( num, NULL);
if ( *root == NULL )
return 1;
else
return 0;
}
binarytree *temp , *p;
temp = *root;
while ( temp != NULL )
{
//p = temp;
if ( num < temp->key )
{
temp = temp->left;
if ( temp == NULL )
printf( "temp = NULL");
}
else if ( num > temp->key)
temp = temp->right;
}
if ( num < temp->key )
temp->left = setnode( num, temp);
else temp->right = setnode( num, temp);
return 0;
}
I don't know why there after some iterations "temp = NULL" is printed , but in while temp != NULL is true!? How???
while ( temp != NULL )
{
//p = temp;
if ( num < temp->key )
{
temp = temp->left;
if ( temp == NULL )
printf( "temp = NULL");
}
else if ( num > temp->key)
temp = temp->right;
}
Upvotes: 1
Views: 103
Reputation: 16304
Becuase you change temp
within the while loop. Remember, a while
expression is tested before every iteration.
We can only assume from your code that temp->left
is null.
Upvotes: 3