Code:
//proc.c
#include <stdio.h>
struct node
{
int value;
struct node *left, *right;
};
void tree_insert(struct node *root, int value);
void tree_destroy(struct node *root);
void tree_print(struct node *root);
void tree_insert(struct node *root, int value)
{
struct node * temp;
if(value < root->value)
{
if(root -> left==NULL) {
temp = (struct node *)malloc(sizeof(struct node));
if(temp == NULL)
{
printf("Could not allocate memory!\n");
return;
}
temp->right = NULL;
temp->left = NULL;
temp->value = value;
printf("Inserted value: %d\n", value);
root -> left = temp;
return;
}
else
tree_insert(root->left, value);
}
else if(value > root->value)
{
if(root -> right==NULL) {
temp = (struct node *)malloc(sizeof(struct node));
if(temp == NULL)
{
printf("Could not allocate memory!\n");
return;
}
temp->right = NULL;
temp->left = NULL;
temp->value = value;
printf("Inserted value: %d\n", value);
root -> right = temp;
return;
}
else
tree_insert(root->right, value);
}
}
void tree_destroy(struct node *root)
{
if(root != NULL)
{
tree_destroy(root->left);
tree_destroy(root->right);
free(root);
}
return;
}
void tree_print(struct node *root)
{
if(root->left)
{
printf("Node value: %d\n", root->value);
tree_print(root->left);
}
if(root->right)
{
tree_print(root->right);
}
}
int main(int argc, char** argv)
{
struct node *root;
int i;
root = NULL;
root = (struct node *)malloc(sizeof(struct node));
if(root == NULL)
{
printf("Could not allocate memory!\n");
return;
}
root->right = NULL;
root->left = NULL;
root->value = 0;
/* if don't allocate memory, you root header is with NULL */
/* And you are sending NULL, not address of NULL*/
/* if you want to send header you can send address of header or make the root extern */
for(i = 1;i < 19;i++)
{
tree_insert(root, i);
}
tree_print(root);
tree_destroy(root);
return 0;
}