Your insert
function is properly adding the new node to the tree. However, as a side effect, it is sometimes changing the global variable root
to point to the left or right node of the root, so that the rest of the tree gets lost. Your insert
function should never change the root, unless root == nullptr
.
Therefore, I suggest you rewrite your function insert
so that it does not use root
at all, but instead receives a pointer to the node as a function parameter. This pointer must be passed by reference and not be value, because the function insert
must be able to change the actual pointer that is passed, if it is nullptr
. In order to accomplish this, you could for example change the function prototype to the following:
void insert( BTNode &*pp_node, int i );
This will also make your recursive function call work properly, as the function can now be rewritten like this:
void insert( BTNode *&node, int i )
{
if ( node == nullptr )
node = new BTNode( i );
else if ( i < node->item )
insert( node->left, i );
else
insert( node->right, i );
}
Your function main
would have to be rewritten like this:
int main()
{
insert( root, 5 );
insert( root, 10 );
insert( root, 1 );
[...]
}
However, since you no longer need root
to be a global variable (because it is passed as a function parameter now), it would probably be better to declare it as a local variable, like this:
int main()
{
BTNode *root = nullptr;
insert( root, 5 );
insert( root, 10 );
insert( root, 1 );
[...]
}
Although this recursive solution to the problem works, an iterative solution would be more efficient. Therefore, you may want to rewrite your function insert
like this:
void insert( BTNode **pp_node, int i )
{
while ( *pp_node != nullptr )
{
if ( i < (*pp_node)->item )
pp_node = &(*pp_node)->left;
else
pp_node = &(*pp_node)->right;
}
*pp_node = new BTNode( i );
}
This solution requires a pointer to a pointer (a so-called double pointer) instead of a reference to a pointer, because references can't be reassigned.
However, since the function prototype of insert
has now changed, you would also have to adapt the function main
accordingly:
int main()
{
BTNode *root = nullptr;
insert( &root, 5 );
insert( &root, 10 );
insert( &root, 1 );
[...]
}