【问题标题】:BST insert not workingBST 插入不工作
【发布时间】:2013-11-15 02:05:47
【问题描述】:

我试图为二叉搜索树实现代码。问题是下面的代码不起作用,但如果我将双指针传递给插入函数,如 insert(struct bst** node, data),它就会起作用。我认为它也应该与传递单指针一起工作。谁能解释这里的错误是什么?

void insert(struct bst* node, int data )
{
    if (node == NULL)
    {
        printf("here with %d\n",data);
        node = (struct bst*)malloc(sizeof(struct bst));
        node->data = data;
        node->left = NULL;
        node->right = NULL;
    }
    if(data < node->data)
    {
        insert(node->left,data);
    }
    else if(data > node->data)
    {
        insert(node->right,data);
    }
}

【问题讨论】:

    标签: c binary-search-tree


    【解决方案1】:

    如果你想改变传递给函数的指针的值,你应该把它作为指针传递给一个指针。

    void alloc_int(int** p)
    {
      *p = malloc(sizeof(int));
    }
    
    int main()
    {
      int* p = NULL;
      alloc_int(&p);
      *p = 10; // here memory for p is allocated so you can use it
      free(p);
      return 0;
    }
    

    在您的示例中也是如此。你必须传递一个指针的地址来改变它的值(指针的值是实际数据的地址)。

    【讨论】:

      【解决方案2】:

      您需要能够修改将成为node 父对象的指针。当您进行递归调用insert(node-&gt;left,data) 时,如果node(新节点的父节点)没有左子节点(left==null),则您调用的是insert(null,data)。然后第一个if 语句将创建新节点并分配其数据,但无法将该节点挂接到树中。此外,由于insert 不返回新节点, 该节点将永远丢失。

      解决此问题的快速方法是返回新节点:

      struct bst *insert(struct bst* node, int data, struct bst* parent )
      { /// Note new return value
          if (node == NULL)
          {
              printf("here with %d\n",data);
              node = (struct bst*)malloc(sizeof(struct bst));
              node->data = data;
              node->left = NULL;
              node->right = NULL;
              return node; /// NEW - send it back to the parent
          }
      
          if(data < node->data)
          {
              node->left = insert(node->left,data); /// save the new child if there wasn't one
              return node; /// otherwise, send back the node so the tree doesn't change.
          }
          else //if(data > node->data) /// On equal keys, add to the right
          {
              node->right = insert(node->right,data);
              return node;
          }
      }
      

      (免责声明:代码尚未测试)

      【讨论】:

        【解决方案3】:

        如果你想改变一个指针的值,你应该传递指针的地址(如struct node **)。

        使用您的代码:

        node = (struct bst*)malloc(sizeof(struct bst));
        

        node 的值在 insert 函数中改变,但不改变调用函数中的变量。

        【讨论】:

          猜你喜欢
          • 2016-08-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-05
          • 1970-01-01
          • 1970-01-01
          • 2012-09-08
          • 2018-03-25
          相关资源
          最近更新 更多