When building the insertion function in binary tree, I use two “if ” statement to track the node( if the value is smaller than the current node,go left;if bigger,go right) . I know the difference between “else if” and “if” before. So initially the result I suppose is both fine with “else if” and with “if” in this condition. I choose “if”. But eventually it turns out it only works for “else if”. When using “if” result shows “segmentation fault”.
Here is the code segment that is correct, the incorrect version changes the “elseif” to “if”.
void insert_another_node(Node* root,int data){
Node* position=root;
Node* prePosition;
while(position!=NULL){
if (data>position->data){
prePosition=position;
position=position->right;
}
else if (data<position->data){
prePosition=position;
position=position->left;
}
else{
return;
}
}
position=malloc(sizeof(Node));
position->data=data;
# position->left=NULL;
position->right=NULL;
if (prePosition==NULL){
root=position;
}
if(data<prePosition->data){
prePosition->left=position;
};
if(data>prePosition->data){
prePosition->right=position;
};
}
I have tried searched the difference between “else if” and “if”. But I think here there shouldn’t have a problem because the condition is independent from each other and save the changes. I want to know why the segment fault happened.