C1 Assignment - 2
C1 Assignment - 2
Set A
a) Implement a Binary search tree (BST) library (btree.h) with
operations – create, search, insert, inorder, preorder and postorder.
Write a menu driven program that performs the
above operations.
btree.h
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 20
if(key==temp->info)
return temp;
else if(key<temp->info)
temp=temp->left;
else
temp=temp->right;
}
return NULL;
}
NODE *insertbst(NODE *root, int num)
{
NODE *newnode,*temp=root,*parent;
newnode=(NODE *)malloc(sizeof(NODE));
newnode->info=num;
newnode->left=newnode->right=NULL;
if(root==NULL)
{
root=newnode;
return root;
}
while(temp!=NULL)
{
parent=temp;
if(num<temp->info)
temp=temp->left;
else
temp=temp->right;
}
if(num<parent->info)
parent->left=newnode;
else
parent->right=newnode;
return(root);
}
inorder(temp->left);
printf("\t%d",temp->info);
inorder(temp->right);
}
}
postorder(temp->left);
postorder(temp->right);
printf("\t%d",temp->info);
}
}
ass1a1.c
#include<stdio.h>
#include "btree.h"
void main()
{
NODE *root=NULL,*temp1;
int ch,num;
clrscr();
do
{
printf("\n1:Create BST");
printf("\n2:Insert");
printf("\n3;search");
printf("\n4:Inodrder");
printf("\n5:Preorder");
printf("\n6:Postorder");
b) Write a program which uses binary search tree library and counts the
total nodes and total leaf nodes in the tree.
#include<stdio.h>
void main()
{
int m[10][10],n,v,i,j;
clrscr();
printf("How many vertices:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("Is there edge between %d->%d (1/0):",i+1,j+1);
scanf("%d",&m[i][j]);
}
}
printf("Adjacency matrix is\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("%d\t",m[i][j]);
}
printf("\n");
}
getch();
Prepared by; Trupti S. Gaikwad Page 1
SYBSc(CS) VCACS, Pune DS and algo II
bst.h
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 20
typedef struct
{
NODE *data[MAXSIZE];
int front,rear;
}QUEUE;
root=newnode;
continue;
}
temp=root;
while(temp!=NULL)
{
parent=temp;
if(num<temp->info)
temp=temp->left;
else
temp=temp->right;
}
if(num<parent->info)
parent->left=newnode;
else
parent->right=newnode;
}
return(root);
}
{
temp=removeq(&q) ;
if(temp==marker)
{
printf("\t cnt=%d",cnt);
cnt=0;
level++;
if(!isempty(&q))
{
addq(&q,marker);
printf("\nLevel %d--->",level);
}
}
else
{
printf("%d\t",temp->info);
if(temp->left)
addq(&q,temp->left);
if(temp->right)
addq(&q,temp->right);
total=total+1;
cnt=cnt+1;
}
}
printf("\ntotal nodes=%d",total);
}
ass2a1.c
#include<stdio.h>
#include<stdlib.h>
#include "bst.h"
void main()
Prepared By: Trupti S.Gaikwad Page 4
SYBSc(CS) VCACS, Pune DS and algo II
{
NODE *root=NULL;
clrscr();
root=createbst(root);
printf("\nLevel order traversal is");
levelorder(root);
getch();
Set B
a) Write a program to sort n randomly generated elements using
Heapsort method.
#include<stdio.h>