So basicaly I was working on a simple program to insert data to a binary tree. The program calls the function for a integer variable of 15 which will be the head node, and then the same function is called for a variable of 12, which should implement the new data on the left branch of the root node. Unfortunately although the first part works correctly, and the root node is printed out, than when the new value should be implemented for the left branch of the root node, nothing happens. Any tips and suggestions are welcome. Thanks.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
int data;
struct node *right;
struct node *left;
} NODE;
void *insert(int ins, NODE *start)
{
NODE *newNode = malloc(sizeof(NODE));
if (start == NULL )
{
newNode->data = ins;
newNode->left = NULL;
newNode->right = NULL;
}
if(ins<start->data)
{
insert(ins, start->left);
}
else if(ins>start->data)
{
insert(ins, start->right);
}
}
int main()
{
int number;
NODE *head;
head=NULL;
number = 15;
head = insert(number, head);
printf("prints the first element (head): %d", head->data);
number = 12;
insert(number, head);
printf("should print the left branch : %d", head->left->data); // <- THIS DOES NOT SHOW UP
}
malloc()into the scope of theif (start == NULL )otherwise every time functioninsert()is called including recursively you will have amalloc()triggered resulting in unused memory that can not be freed withfree().