C program for creating and traversing the binary search tree of characters

				
					/*program for creating and traversing the binary search tree*/
#include<stdio.h>
#include<stdlib.h>
typedef struct BST
{
char d;

/*declaring a structure to create a node*/
struct BST *lc,*rc;
}node;
void insert(node *,node *);
void preorder(node *);
void inorder(node *);
void postorder(node *);
/*main program*/
void main()
{
int choice;
char ans='N';
int key;
node *nn,*root,*parent;
root=NULL;
printf("\n program for binary search tree");
do
{
printf("\n 1.create");

printf("\n 2.resurcive traverse");
printf("\n 3.exit");

printf("\n enter your choice");
scanf("%d",&choice);
switch(choice) /*switch case*/
{
case 1:
do
{
nn=(node *)malloc(sizeof(node));

printf("\n enter the elements");
nn->lc=NULL;
nn->rc=NULL;
scanf(" %c",&nn->d);
if(root==NULL)
root=nn;
else
insert(root,nn);
printf("\n want to enter more elements?(Y/N)");
scanf(" %c",&ans);
}while(ans=='y');
break;
case 2:
if(root==NULL)
printf("tree is not created");
else
{
printf("\n the inorder display:");
inorder(root);
printf("\n the preorder display:");
preorder(root);

printf("\n the postorder display:");
postorder(root);
}
break;

} /*end of switch case*/ }while(choice!=3);
}
/*insertion operation*/
void insert(node *root,node *nn)
{

int c,d;
c=nn->d;
d=root->d;
if(c<d)
{

if(root->lc==NULL)
root->lc=nn;
else
insert(root->lc,nn);
}
}
/*inorder traversal*/
void inorder(node *temp)
{
if(temp!=NULL)

{
inorder(temp->lc);
printf(" %c",temp->d);
inorder(temp->rc);
}

}
/*preorder traversal*/
void preorder(node *temp)
{

if(temp!=NULL)
{
printf(" %c",temp->d);

preorder(temp->lc);
preorder(temp->rc);
}
}

/*postorder traversal*/
void postorder(node *temp)

{
if(temp!=NULL)
{

postorder(temp->lc);
postorder(temp->rc);
printf(" %c",temp->d);
}
}
				
			

Leave a Reply