Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Binary Search Tree in C

Binary Search Tree 

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define null 0
typedef struct tree*node;
node insert(int,node t);
void find(node t,int x);
node findmin(node t);
void findmax(node t);
void display(node t);

struct tree
{
int data;
struct tree*right,*left;
}*root;
void main()
{
node t=null;
int data,s,i=0,n,x,ch;
char c;
clrscr();
printf("\n enter the number of elements in the tree\n");
scanf("%d",&n);
printf("elements are:\n");
while(i<n)
{
scanf("%d",&data);
t=insert(data,t);
i++;
}
printf("1.find\t2.findmin\t3.findmax\t4.display\t5.delete\t6.exit");
do
{
printf("\n enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("enter the element to search\n");
scanf("%d",&s);
find(t,s);
break;
case 2:
findmin(t);
break;
case 3:
findmax(t);
break;
case 4:
printf("elements displayed in inorder format\n");
display(t);
break;
default:
printf("exit");
exit(0);
}
}
while(ch<9);
getch();
}
node insert(int x,node t)
{
struct tree*newnode;
newnode=malloc(sizeof(struct tree));
if(newnode==null)
printf("out of space\n");
else
{
if(t==null)
{
newnode->data=x;
newnode->left=null;
newnode->right=null;
t=newnode;
}
else
{
if(x<t->data)
t->left=insert(x,t->left);
else
t->right=insert(x,t->right);
}
}
return t;
}
void find(node t,int x)
{
if(t==null)
printf("search element not found");
else
{
if(t->data==x)
printf("search element %d is found",x);
else if(x<t->data)
find(t->left,x);
else
find(t->right,x);
}
}
node findmin(node t)
{
if(t!=null)
{
if(t->left==null)
{
printf("\n the minimum element in the tree is %d",t->data);
return t;
}
else
findmin(t->left);
}
}
void findmax(node t)
{
if(t!=null)
{
if(t->right==null)
printf("\n the maximum element in the tree is %d",t->data);
else
findmax(t->right);
}
}
void display(node t)
{
if(t!=null)
{
display(t->left);
printf("%d\t",t->data);
display(t->right);
}
}