I have tried to build a binary tree for integer storage as the following code. There seems no error message in Eclipse. But when I tried to run it, the program stop instantly with windows stop error notification.
Node* insertNode(Node *root, int value){
Node* temp = root;
if(temp != NULL){
while(temp->left != NULL || temp->right != NULL){
if(value < temp->data){
temp = temp->left;
}
else{
temp = temp->right;
}
}
}
Node* new = (Node*)malloc(sizeof(Node));
if(value < temp->data){
new->data = value;
new->left = new->right = NULL;
temp->left = new;
return temp;
}
else{
new->data = value;
new->left = new->right = NULL;
temp->right = new;
return temp;
}
}
This is a function for creating the binary tree. I would like to get a value any save it to the existing binary tree. After the right place has been found in the tree. I would like to create a new node with the value and store that as the pointer of parent. Here is the struct of Node.
struct Node{
int data;
struct Node *left;
struct Node *right;
};
typedef struct Node Node;
root = NULL, then in your insert function you dereferncetemp, e.g.if(value < temp->data)invoking Undefined Behavior (and a likely SegFault). Handle the case where you are adding the 1st value to your tree.