我的二叉树插入逻辑中的缺陷在哪里?

时间:2017-01-30 03:13:38

标签: c++ algorithm tree

我的解决方案就像

/*
Node is defined as 

typedef struct node
{
   int data;
   node * left;
   node * right;
}node;

*/


node * insert (node * root, int value)
{
   bool inTreeAlready = false;
   node * cur = root;
   while(cur != NULL)
   {
       if(cur->data < value)
           cur = cur->right;
       else if(cur->data > value)
           cur = cur->left;
       else
       {
           inTreeAlready = true;
           break;
       }
   }
   if(!inTreeAlready)
   {
       cur = new node; 
       cur->data = value;
       cur->left = NULL;
       cur->right = NULL;
   }   
   return root;
}

问题的提示说你应该在插入后返回树的根。

由于输出

,这显然是错误的
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

这不是很具描述性。

我已经仔细检查了我的逻辑,不知道这笔交易是什么。

1 个答案:

答案 0 :(得分:0)

您没有将新节点添加到树中。这是修改后的版本。

node * insert (node * root, int value)
{
   bool inTreeAlready = false;
   node * cur = root;
   node *parent;
   bool right;
   while(cur != NULL)
   {
       parent = cur;
       if(cur->data < value)
       {
           cur = cur->right;
           right = true;
       }
       else if(cur->data > value)
       {
           cur = cur->left;
           right = false;
       }
       else
       {
           inTreeAlready = true;
           break;
       }
   }
   if(!inTreeAlready)
   {
       cur = new node; 
       cur->data = value;
       cur->left = NULL;
       cur->right = NULL;
       if(root == NULL) root = cur;
       else if(right) parent->right = cur;
       else parent->left = cur;
   }   
   return root;
 }