Pranjal Misra Pranjal Misra - 1 month ago 5
C++ Question

insert operation in Binary tree error?

I am getting error in the insertion operation for the binary tree the question link is( https://www.hackerrank.com/challenges/binary-search-tree-insertion )
my code is :

insert(node * root, int value)
{
int x = 0;
node* r = root;
node* xx;
while(x==0)
{
while(value<r->data&&r->left!=NULL)
{
r=r->left;
}
if(value<r->data&&r->left == NULL)
{
xx->data = value;
r->left = xx;
break;
}
while(value>r->data && r->right!=NULL)
{
r = r->right;
}
if(value>r->data&& r->right == NULL)
{
xx->data = value;
r->right =xx;
break;
}
}
return root;
}


The error that I am getting from the hackerrank is as follows:

Wrong Answer!
Some possible errors:


  1. You returned a NULL value from the function.

  2. There is a problem with your logic

  3. You are printing some value from the function


Answer

For starters, you need to allocate a new node on each insertion.

Start your declaration like this:

node* insert(node * root, int value)
{
    node* xx = new node();
    xx->left = NULL;
    xx->right = NULL;
    xx->data = value;