【问题标题】:I'm having trouble with the insert function for my binary search tree我的二叉搜索树的插入函数有问题
【发布时间】:2011-11-30 15:12:21
【问题描述】:

基本上我的插入函数中发生的事情是触发将节点放置在我的 bst 中根右侧的部分导致程序崩溃,我不知道为什么。插入函数如下。

node* insert(node *root, node *element)
{

    // Inserting into an empty tree.
    if (root == NULL)
        return element;
    else {

        // element should be inserted to the right.
        if (element->bk->key < root->bk->key) {

            printf("Inserting in left position.\n");
            // There is a right subtree to insert the node.
            if (root->left != NULL)
                root->left = insert(root->left, element);

            // Place the node directly to the right of root.
            else
                root->left = element;
        }

        // element should be inserted to the left.
        else {

            // There is a left subtree to insert the node.
            if (root->right != NULL)
                root->right = insert(root->right, element);

            // Place the node directly to the left of root.
            else
                root->right = element;
        }

        // Return the root pointer of the updated tree.
        return root;
    }
}

【问题讨论】:

  • 请你修复你的代码缩进。
  • 你试过在调试器中运行它吗?这会告诉你它在哪条线路上崩溃了,以及为什么。
  • 在你调用这个函数之前,告诉我们你是如何初始化element的。

标签: c search insert tree


【解决方案1】:

崩溃的最佳候选者是

if (element->bk->key < root->bk->key)

所以element-&gt;bkroot-&gt;bkNULL 或指向无处。

【讨论】:

    【解决方案2】:

    问题中的信息太少,无法确定,所以我们必须猜测。我认为最可能的罪魁祸首是element 可能没有正确初始化。这可能意味着以下任何一种:

    1. element 未指向 node 的有效实例(未初始化的指针、悬空指针等)。
    2. element-&gt;bk 为 NULL 或不是有效指针。
    3. 输入函数时element-&gt;left 不为 NULL。
    4. 输入函数时element-&gt;right 不为 NULL。

    顺便说一句,这个函数比它需要的复杂得多:

    node* insert(node *root, node *element) {
        if (root == NULL)
            return element; // Inserting into an empty tree.
        else {
            if (element->bk->key < root->bk->key) {
                printf("Inserting in left position.\n");
                root->left = insert(root->left, element);
            } else {
                printf("Inserting in right position.\n");
                root->right = insert(root->right, element);
            }
            // Return the root pointer of the updated tree.
            return root;
        }
    }
    

    注意两个if (root-&gt;X != NULL) 语句和两个else 子句是不必要的。使用root==NULL 调用函数会做正确的事情,这要感谢顶部的if (root==NULL) 检查。

    【讨论】:

      【解决方案3】:

      我将采取的调试步骤:

      1. 在调试器中运行
      2. 如果做不到这一点,请在使用之前使用 fflush(stdout) 打印所有内容,这样如果您没有打印,您就知道那是初始化不良的部分。
      3. 我会修复您的 cmets,以便它们真正反映您正在做的事情(在 cmets 中左右是向后的),这样当您感到疲倦/沮丧时,您就不会感到困惑。
      4. 就像 aix 所说的简化,这可能会解决您的问题(尽管可能不会),或者至少让调试器中的单步调试、思考和阅读变得更简单。

      如前所述,如果您给我们调用/初始化,我们可以提供更多帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-30
        • 1970-01-01
        • 1970-01-01
        • 2015-02-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多