Pranjal Misra - 3 months ago 11

C++ Question

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:

- You returned a NULL value from the function.
- There is a problem with your logic
- 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;
```