I'm new to C and I just started learning how to use pointers. I'm trying to create a function (r) that adds to a bst depending on if the parameter (int n) is greater than the root nodes value. However, I keep getting segmentation fault (core dumped) after running the following code. How do I fix it so that it can run normally without error.
struct node {
int data;
struct node *left;
struct node *right;
}node;
struct node* newNode(int data){
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
void r (int n, struct node* root);
int main() {
struct node *root = newNode(1);
printf("%d", root->data);
r(10, root);
return 0;
}
void r(int n, struct node* root){
if(n > root->left->data){
root->right = newNode(n);
printf("New right is: %d\n", root->right->data);
}
else if(n < root->left->data){
int a = root->left->data;
root->left->data = n;
root->right->data = a;
printf("New left is: %d\n", root->left->data);
}
return;
}
r(10, root)you haveif (n > root->left->data)..In this caseroot->leftis NULL.