You are on page 1of 2

Name of the Program:week5

Week 5: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 Postorder.
#include <stdio.h>
#include<string.h>
#include <stdlib.h>
struct BST
{
char data;
struct BST *left,*right;
}node;
struct BST* root=NULL,*temp,*cur;
void create()
{
char c[10];
temp=root;
cur=(struct BST*)malloc(sizeof(struct
BST));
printf("\n enter character:\n");
fflush(stdin);
scanf("%s",c);
cur->data=c[0];
cur->left=NULL;
cur->right=NULL;
if(temp==NULL)
root=cur;
else
{
while(temp!=NULL)
{
if((cur->data))<(temp->data))
{
if(temp->left==NULL)
{
temp->left=cur;
return;
}
else
temp=temp->left;
}
else
{
if(temp->right==NULL)
{
temp->right=cur;
return;
}
else
temp=temp->right;

}//else
}//while
}//else
}//create
void postorder(struct BST *temp)
{
if(temp!=NULL)
{
postorder(temp->left);
postorder(temp->right);
printf("\t%c",temp->data);
}
}
int main()
{
int ch;
printf("\nmenu options\n");
printf("1.Create\n2.Postorder\n3.exit\n");
while(1)
{
printf("\nenter ur choice");
scanf("%d",&ch);
switch(ch)
{
case 1:create();
break;
case 2:printf("Postorder
Traversal\n");
postorder(root);
break;
case 3:exit(0);
default:printf("invalid
choice\n");
}//switch
}//while
}//main
Output:
$ ./a.out
menu options
1.Create
2.Postorder
3.exit
enter ur choice1

Name of the Program:week5


enter character:
D

enter character:
E

enter ur choice1
enter ur choice1
enter character:
F

enter character:
C

enter ur choice1
enter ur choice1
enter character:
B

enter character:
A

enter ur choice1
enter character:
G
enter ur choice1

enter ur choice2
Postorder Traversal
A
C
B
E
G
F
D
enter ur choice3
[13r21a0507@mysqldbserver week5]$

You might also like