42)Write a C program to read N number and sort in binary search tree structure.


#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node* lchild;
struct node* rchild;
};
struct queue
{
struct node *data[10];
int front,rear;
};
void insert(struct queue *,struct node *);
struct node * del(struct queue *);
int isempty(struct queue *);
struct node* create(struct node*);
void bfs(struct node *);
void main()
{
struct node* root=NULL;
root=(struct node*)create(root);
printf(“\n\nLEVELWISE NODES OF TREE \n”);
bfs(root);
getch();
}
struct node* create(struct node* root)
{
struct node* temp,*newn;
int i,size;
clrscr();
printf(“\nENTER THE SIZE”);
scanf(“%d”,&size);
for(i=0;i<size;i++)
{
newn=(struct node*)malloc(sizeof(struct node));
newn->lchild=newn->rchild=NULL;
printf(“\nENTER THE DATA”);
scanf(“%d”,&newn->data);
if(root==NULL)
{
root=newn;
}
else
{
temp=root;
while(temp!=NULL)
{
if(temp->data>newn->data)
{
if(temp->lchild!=NULL)
{
temp=temp->lchild;
}
else
{
temp->lchild=newn;
break;
}
}
else
{
if(temp->rchild!=NULL)
{
temp=temp->rchild;
}
else
{
temp->rchild=newn;
break;
}
}
} //while
}//else
}//for
return root;
}
void insert(struct queue *q,struct node *temp)
{
q->data[++q->rear]=temp;
}
struct node * del(struct queue *q)
{
return(q->data[++q->front]);
}
int isempty(struct queue *q)
{
if(q->front==q->rear)
return 1;
else
return 0;
}
void bfs(struct node *root)
{
struct queue q;
struct node *temp;
q.front=q.rear=-1;
temp=root;
insert(&q,temp);
while(!isempty(&q))
{
temp=del(&q);
printf(“%d -> “,temp->data);
if(temp->lchild!=NULL)
insert(&q,temp->lchild);
if(temp->rchild!=NULL)
insert(&q,temp->rchild);
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s