BST insert not working

六月ゝ 毕业季﹏ 提交于 2019-12-02 10:21:15

If you want to change the value of the pointer passed to a function, you should pass it as pointer to a pointer.

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

The same thing in your example. You have to pass an address of pointer to change its value (value of the pointer is address of actual data).

You need to be able to modify the pointers in what will become the parents of node. When you make the recursive call insert(node->left,data), if node (the parent of the new node) has no left child (left==null), you are calling insert(null,data). The first if statement will then create the new node and assign its data, but there will be no way to hook that node into the tree. Also, since insert doesn't return the new node, the node is lost forever.

A quick hack to fix this would be to return the new node:

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

(disclaimer: code not yet tested)

longdeqidao

If you want to change a pointer's value, you should pass the address of the pointer (as struct node **).

With your code:

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

the value of node changes in the insert function, but doesn't change the variable in the calling function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!