I tried to implement Binary search tree through C proggramming. I wrote only two functions. The program compiles perfectly. But when it is being run, it works upto the point of asking user to "Enter the data to be inserted". After the data is inserted the program is being stopped.
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int info;
struct Node *left;
struct Node *right;
}node;
node* insert(node *root, int data);
void inorder(node* root);
int main()
{
int data,choice;
node *root;
printf("----------------MENU---------------\n");
printf("1. Insert\n");
printf("2.Inorder traversal\n");
printf("3.Exit\n");
while(1)
{
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the data to be inserted: ");
scanf("%d",&data);
root=insert(root,data);
break;
case 2:inorder(root);
break;
case 3:
exit(0);
}
}
return 0;
}
node* insert(node *root, int data)
{
if(root==NULL)
{
root=(node *)malloc(sizeof(node));
root->info=data;
root->left=root->right=NULL;
return root;
}
else if(data<=root->info)
{
root->left=insert(root->left,data);
return root;
}
else if(data>=root->info)
{
root->right=insert(root->right,data);
return root;
}
}
void inorder(node* root)
{
if(root==NULL)
return;
else
{
inorder(root->left);
printf("%d",root->info);
inorder(root->right);
}
}
root(so it is not reliably NULL); you pass it toinsert();insert()uses it and things go haywire.