Closed. This question is off-topic。它当前不接受答案。
想改善这个问题吗? Update the question,因此它是on-topic,用于堆栈溢出。
4年前关闭。
在二进制搜索树中插入值时给出分段错误。
这是hackerrank问题,因此只需编写此方法
这是我写的
我不明白为什么这段代码给我分段错误。
欢迎所有建议。
想改善这个问题吗? Update the question,因此它是on-topic,用于堆栈溢出。
4年前关闭。
在二进制搜索树中插入值时给出分段错误。
这是hackerrank问题,因此只需编写此方法
这是我写的
typedef struct node
{
int data;
node * left;
node * right;
}node;
node * insert(node * root, int value)
{
node* temp = root;
node* temp1 = new node();
node* prev = NULL ;
while(temp != NULL){
prev= temp;
if(value >= temp->data)
temp = temp->right;
else
temp = temp->left;
}
temp1->data = value;
temp1->left = NULL;
temp1->right = NULL;
if(prev->data >= value)
prev->left = temp1;
else
prev->right = temp1;
return root;
}
我不明白为什么这段代码给我分段错误。
欢迎所有建议。
最佳答案
当使用递归使代码更简单时,无需使代码复杂。
node * insert(node * root, int value)
{
if(root==NULL)
{
root=new node;
root->data=value;
root->left=NULL;
root->right=NULL;
return root;
}
else if(root->data>value)
{
root->left=insert(root->left,value);
return root;
}
else
{
root->right=insert(root->right,value);
return root;
}
}
关于c++ - 二进制搜索插入中的段错误c++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31875609/