Simple enough program so far: a binary tree made up of nodes containing an integer value, and a pointer to the left and right branch of the node.
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int val;
struct node *left;
struct node *right;
} Node;
void insert(Node *root, int val);
int main(void){
Node *root = NULL;
insert(root, 5);
insert(root, 3);
printf("%d\n", root->val);
return 0;
}
void insert(Node *root, int val){
if(root == NULL){ // Create tree if root is empty
root = malloc(sizeof(struct node));
root->val = val;
root->left = NULL;
root->right = NULL;
} else if(val < root->val){ // branch to left of tree if new value is less than root value
if(root->left == NULL){
root->left = malloc(sizeof(struct node));
}
root->left->val = val;
} else if(val > root->val){ // branch to right of tree if new value is greater than root value
if(root->right == NULL){
root->right = malloc(sizeof(struct node));
}
root->right->val = val;
}
}
For whatever reason, the insertion goes fine. I can input both 5 and 3 (arbitrary) fine. But I can't print out the value '5' that should be in root->val? The program just completely crashes. Have I overlooked something?