Professional Documents
Culture Documents
Design, Develop and Implement 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 Postorder
c. Search the BST for a given element (KEY) and report the appropriate message
d. Exit
Program:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *lchild;
struct node *rchild;
};
nodepointer getnode()
{
nodepointer x;
x=(nodepointer)malloc(sizeof(struct node));
return x;
}
nodepointer insert(int item, nodepointer root)
{
nodepointer temp,cur,prev;
temp=getnode();
temp->info=item;
temp->lchild=temp->rchild=NULL;
if(root==NULL)
{
root=temp;
return root;
}
else
{
prev=NULL;
cur=root;
while(cur!=NULL)
{
prev=cur;
if(temp->info < cur->info)
cur=cur->lchild;
else if(temp->info > cur->info)
cur=cur->rchild;
else
{
printf("Duplicate Node\n");
return root;
}
}
if(temp->info > prev->info)
prev->rchild=temp;
else
prev->lchild=temp;
return root;
}
}
void preorder(nodepointer root)
{
if(root!=NULL)
{
printf("%d\t",root->info);
preorder(root->lchild);
preorder(root->rchild);
}
}
struct node
{
int info;
struct node *lchild;
struct node *rchild;
};
nodepointer getnode()
{
nodepointer x;
x=(nodepointer)malloc(sizeof(struct node));
return x;
}
nodepointer insert(int item, nodepointer root)
{
nodepointer temp,cur,prev;
temp=getnode();
temp->info=item;
temp->lchild=temp->rchild=NULL;
if(root==NULL)
{
root=temp;
return root;
}
else
{
prev=NULL;
cur=root;
while(cur!=NULL)
{
prev=cur;
if(temp->info < cur->info)
cur=cur->lchild;
else if(temp->info >= cur->info) /*Changes are shown in RED Colour*/
cur=cur->rchild;
}
if(temp->info >= prev->info) /*Changes are shown in RED Colour*/
prev->rchild=temp;
else
prev->lchild=temp;
return root;
}
}