#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* left;
struct node* right;
};
struct node* root = NULL;
struct node* q[100];
int insert(int);
void bfs();
int main()
{
int size=0;
int choice;
while(1)
{
printf("Enter 1-> to insert the data\n");
printf("Enter 2->to display\n");
printf("Enter 3 - > to exit");
printf("Enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1 : size= insert(size);
break;
case 2 : bfs(size);
break;
case 3 : exit(0);
break;
}
}
}
int insert(int size)
{
size++;
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter data");
scanf("%d",&temp->data);
temp->left = NULL;
temp->right = NULL;
if(root==NULL)
{
else
{
struct node* p = root;
struct node* q = NULL;
while(p!=NULL)
{
q = p;
if(temp->data>p->data)
{
p=p->right;
}
else
{
p = p->left;
}
}
if(temp->data>q->data)
{
q->right = temp;
}
else
{
q->left = temp;
}
}
return size;
}
void bfs(int size)
{
int c= 0,r=0;
q[c] = root;
if(q[c]==NULL)
{
printf("Nothing to display");
}
else
{
int i;
while(q[c]!=NULL)
{
if(c==size-1)
{
break;
}
if(q[c]->left!=NULL && q[c]->right!=NULL)
{
q[++r] = q[c]->left;
q[++r] = q[c]->right;
c++;
}
else if(q[c]->left!=NULL && q[c]->right==NULL)
{
q[++r] = q[c]->left;
c++;
}
else if(q[c]->left==NULL && q[c]->right!=NULL)
{
q[++r] = q[c]->right;
c++;
}
else if(q[c]->left==NULL && q[c]->right==NULL)
{
c++;
}
}
for(i=0;i<=r;i++)
{
printf("%d\t",q[i]->data);
}
}
}
#include<stdlib.h>
struct node{
int data;
struct node* left;
struct node* right;
};
struct node* root = NULL;
struct node* q[100];
int insert(int);
void bfs();
int main()
{
int size=0;
int choice;
while(1)
{
printf("Enter 1-> to insert the data\n");
printf("Enter 2->to display\n");
printf("Enter 3 - > to exit");
printf("Enter your choice\n");
scanf("%d",&choice);
switch(choice)
{
case 1 : size= insert(size);
break;
case 2 : bfs(size);
break;
case 3 : exit(0);
break;
}
}
}
int insert(int size)
{
size++;
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter data");
scanf("%d",&temp->data);
temp->left = NULL;
temp->right = NULL;
if(root==NULL)
{
root = temp;
}else
{
struct node* p = root;
struct node* q = NULL;
while(p!=NULL)
{
q = p;
if(temp->data>p->data)
{
p=p->right;
}
else
{
p = p->left;
}
}
if(temp->data>q->data)
{
q->right = temp;
}
else
{
q->left = temp;
}
}
return size;
}
void bfs(int size)
{
int c= 0,r=0;
q[c] = root;
if(q[c]==NULL)
{
printf("Nothing to display");
}
else
{
int i;
while(q[c]!=NULL)
{
if(c==size-1)
{
break;
}
if(q[c]->left!=NULL && q[c]->right!=NULL)
{
q[++r] = q[c]->left;
q[++r] = q[c]->right;
c++;
}
else if(q[c]->left!=NULL && q[c]->right==NULL)
{
q[++r] = q[c]->left;
c++;
}
else if(q[c]->left==NULL && q[c]->right!=NULL)
{
q[++r] = q[c]->right;
c++;
}
else if(q[c]->left==NULL && q[c]->right==NULL)
{
c++;
}
}
for(i=0;i<=r;i++)
{
printf("%d\t",q[i]->data);
}
}
}
No comments:
Post a Comment