BST插入不起作用

时间:2013-11-15 02:05:47

标签: c binary-search-tree

我正在尝试为二叉搜索树实现代码。问题是以下代码不起作用,但如果我传递双指针插入函数如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);
    }
}

3 个答案:

答案 0 :(得分:1)

如果要更改指针的值,则应传递指针的地址(struct node **)。

使用您的代码:

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

node函数中insert的值发生了变化,但不会更改调用函数中的变量。

答案 1 :(得分: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 :(得分:1)

您需要能够修改将成为node父母的指针。当您进行递归调用insert(node->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;
    }
}

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

相关问题