【发布时间】:2015-12-18 09:03:11
【问题描述】:
有人可以解释一下下面的二进制搜索插入代码有什么问题吗?当我尝试插入第二个元素时,它会出现分段错误。
node * insert(node * root, int value)
{
if(root == NULL){
node *newnode = (node *)malloc(sizeof(node));
newnode->data = value;
newnode->left = NULL;
newnode->right = NULL;
root = newnode;
}
else{
if(root->data > value)
insert(root->left, value);
if(root->data < value)
insert(root->right, value);
}
return root;
}
int main(){
node* root = NULL;
root = insert(root, 5);
root = insert(root, 10);
}
【问题讨论】:
-
您好,欢迎来到 StackOverflow。请添加您的节点类型的声明。您确定在 main() 函数中修改了根值吗?
-
你为什么要返回root?
-
@BlueMoon93:因为它是这样被修改的?
-
@undur_gongor:那么他不应该有“root->left=insert(root->left, value);”吗?我很困惑
-
@BlueMoon93:在某些情况下,必须修改根节点。您可以通过将指针传递给根指针或返回(可能已修改的)根来完成此操作。 an111 使用了第二种方法。目前,仅当树为空时才修改根节点。稍后可能由于重新平衡而需要修改。
标签: c binary-search-tree