在二叉树中插入操作错误?

insert operation in Binary tree error?

我在二叉树的插入操作中遇到错误,问题 link 是(https://www.hackerrank.com/challenges/binary-search-tree-insertion) 我的代码是:

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;
} 

我从 hackerrank 得到的错误如下:

回答错误! 一些可能的错误:

  1. 您从函数返回了 NULL 值。
  2. 你的逻辑有问题
  3. 您正在打印函数中的一些值

对于初学者,您需要在每次插入时分配一个新节点。

像这样开始你的声明:

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