You are on page 1of 5

10.

Develop a menu driven Program in C for the following operations on Binary Search Tree
(BST) of Integers .
a. Create a BST of N Integers: 6, 9, 5, 2, 8, 15, 24, 14, 7, 8, 5, 2
b. Traverse the BST in Inorder, Preorder and Post Order
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit

#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *left;
struct Node *right;
};

struct Node *CreateNode(int key)


{
struct Node *newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=key;
newNode->left=newNode->right=NULL;
return newNode;
};

struct Node* insert(struct Node *root, int key)


{
if(root==NULL)
{
return CreateNode(key);
}
if(key<root->data)
{
root->left=insert(root->left,key);
}
else if(key>root->data)
{
root->right=insert(root->right,key);
}
return root;
}

void inorder(struct Node *root)


{
if(root!= NULL)
{
inorder(root->left);
printf("%d\t", root->data);
inorder(root->right);
}
}

void preorder(struct Node *root)


{
if(root!= NULL)
{
printf("%d\t", root->data);
preorder(root->left);
preorder(root->right);
}
}

void postorder(struct Node *root)


{
if(root!= NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d\t", root->data);
}
}

void search(struct Node *root, int key)


{
if(root==NULL)
{
printf("\nElement %d not found in BST",key);
return;
}
if(key==root->data)
{
printf("\nElement %d found in BST", root->data);
}
else if(key<root->data)
{
search(root->left,key);
}
else
search(root->right,key);
}

void main()
{
int data, ch, i, n;
struct Node *root=NULL;
while(1)
{
printf("\n\n1.Insertion in Binary Search Tree");
printf("\n2.Search Element");
printf("\n3.Inorder\n4.Preorder\n5.Postorder\n6.Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: printf("\nEnter the no. of nodes: " );
scanf("%d",&n);
printf("\nEnter the %d values: ",n);
for(i=0;i<n;i++)
{
scanf("%d",&data);
root=insert(root,data);
}
break;
case 2: printf("\nEnter the element to search: ");
scanf("%d",&data);
search(root,data);
break;
case 3: printf("\nInorder Traversal: \n");
inorder(root);
break;
case 4: printf("\nPreorder Traversal: \n");
preorder(root);
break;
case 5: printf("\nPostorder Traversal: \n");
postorder(root);
break;
case 6: exit(0);
default:printf("\nWrong option");
break;
}
}
}

You might also like