Monday, 11 December 2017

Write a C program that uses functions to perform the following:
a) Create a binary search tree of characters
b) Traverse the above Binary search tree recursively in Post-order.

Implementation of above problem:
#include<stdio.h>
#include<stdlib.h>
typedef struct BST 
{
char d; /*declaring a structure to create a node*/
struct BST *lc,*rc;
}node;
/* implementation of insert function */
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);
}
}
/* implementation of inorder function */
void inorder(node *temp) 
{
if(temp!=NULL) 
{
inorder(temp->lc);
printf(" %c",temp->d);
inorder(temp->rc);
}
}
/* implementation of preorder function */
void preorder(node *temp) 
{
if(temp!=NULL) 
{
printf(" %c",temp->d);
preorder(temp->lc);
preorder(temp->rc);
}
}
/* implementation of postorder function */
void postorder(node *temp) 
{
if(temp!=NULL) 
{
postorder(temp->lc);
postorder(temp->rc);
printf(" %c",temp->d);
}
}
/* Implementation of main function */
void main() 
{
int choice;
char ans='N';
int key;
node *nn,*root,*parent;
root=NULL;
while(1) 
{
printf("\n\n *MENU - Binary Search Tree *");
printf("\n 1. Create");
printf("\n 2. Tree Traversals");
printf("\n 3. Exit");
printf("\n Please select the operation: ");
scanf("%d",&choice);
switch(choice) 
{
case 1: do 
{
nn=(node *)malloc(sizeof(node));
printf("\n Please enter the element to be insert: ");
nn->lc = NULL;
nn->rc = NULL;
scanf(" %c",&nn->d);
if(root == NULL)
root=nn;
else
insert(root,nn);
printf("\n Want to insert more elements? (Y/N): ");
scanf(" %c",&ans);
}
while(ans=='y');
break;
case 2: 
if(root==NULL)
printf("\n\n Tree is not created");
else 
{
printf("\n\n The inorder display : ");
inorder(root);
printf("\n\n The preorder display : ");
preorder(root);
printf("\n\n The postorder displayb:");
postorder(root);
}
break;
case 3: exit(0);
}
}
}


Thanks
Mukesh Rajput

No comments:

Post a Comment

Thanks
Mukesh Rajput