BINARY SEARCH TREE CREATION THROUGH C
#include<stdio.h>
#include<stdlib.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
int pre(struct tree *root)
{
if(root!=NULL)
{
printf("%d ",root->data);
pre(root->left);
pre(root->right);
}
}
struct tree *Insert_node(struct tree *root)
{
struct tree *temp,*ptr,*prev=NULL;
temp=(struct tree *)malloc(sizeof(tree));
int n;
printf("enter data");
scanf("%d",&n);
temp->data=n;
temp->left=NULL;
temp->right=NULL;
if(root==NULL)
{
root=temp;
}
else
{
ptr=root;
while(ptr!=NULL)
{
prev=ptr;
if(ptr->data>temp->data)
{
ptr=ptr->left;
}
else if(ptr->data<temp->data)
{
ptr=ptr->right;
}
else if(ptr->data==temp->data)
{
printf("duplticate key");
break;
}
}
if(temp->data<prev->data)
{
prev->left=temp;
}
else
{
prev->right=temp;
}
}
return root;
}
int main()
{
struct tree *root=NULL;
int n;
while(1)
{
printf("enter your choice 1 for insert node 2 for pre_order traverse 0 for exit");
scanf("%d",&n);
switch(n)
{
case 1:
root=Insert_node(root);
break;
case 2:
pre(root);
break;
case 0:
exit(0);
}
}
}
#include<stdlib.h>
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
int pre(struct tree *root)
{
if(root!=NULL)
{
printf("%d ",root->data);
pre(root->left);
pre(root->right);
}
}
struct tree *Insert_node(struct tree *root)
{
struct tree *temp,*ptr,*prev=NULL;
temp=(struct tree *)malloc(sizeof(tree));
int n;
printf("enter data");
scanf("%d",&n);
temp->data=n;
temp->left=NULL;
temp->right=NULL;
if(root==NULL)
{
root=temp;
}
else
{
ptr=root;
while(ptr!=NULL)
{
prev=ptr;
if(ptr->data>temp->data)
{
ptr=ptr->left;
}
else if(ptr->data<temp->data)
{
ptr=ptr->right;
}
else if(ptr->data==temp->data)
{
printf("duplticate key");
break;
}
}
if(temp->data<prev->data)
{
prev->left=temp;
}
else
{
prev->right=temp;
}
}
return root;
}
int main()
{
struct tree *root=NULL;
int n;
while(1)
{
printf("enter your choice 1 for insert node 2 for pre_order traverse 0 for exit");
scanf("%d",&n);
switch(n)
{
case 1:
root=Insert_node(root);
break;
case 2:
pre(root);
break;
case 0:
exit(0);
}
}
}
Comments
Post a Comment