Write c program to perform following functions on tree 1) Create tree 2) Display tree in preorder 3) Search an element from tree
Tree
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
//To create structure tree
struct tree
{
int data;
struct tree *left, *right;
};
typedef struct tree node;
//To define functions
void preorder(node *);
node * create(node *);
void search(node *, int);
void main()
{
node *root=NULL;
int ch,s;
do
{
printf("\n1.Create tree. \n2.Display tree in preorder. \n3.Search an element \n4.Exit");
printf("\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
root=create(root);
break;
case 2:
printf("\nContent of Tree in Preorder is: ");
preorder(root);break;
case 3:
printf("\nEnter the element which you want to search: ");
scanf("%d",&s);
search(root,s);
break;
}
}while(ch!=4);
}
//To create tree
node *create(node *root)
{
char ch;
node *ptr=NULL, *temp=NULL;
do
{
temp=(node *)malloc(sizeof(node));
printf("\nEnter data: ");
scanf("%d",&temp->data);
temp->left=NULL;
temp->right=NULL;
if(root==NULL)
root=temp;
else
{
ptr=root;
while(ptr!=NULL)
{
if(ptr->data>temp->data)
{
if(ptr->left==NULL)
{
ptr->left=temp;
break;
}
else
ptr=ptr->left;
}
else
{
if(ptr->data<temp->data)
{
if(ptr->right==NULL)
{
ptr->right=temp;
break;
}
else
ptr=ptr->right;
}
}
}
}
printf("\nDo you want to add more(y/n): ");
scanf(" %c",&ch);
}while(ch!='n');
return root;
}
//To display tree in preorder
void preorder(node *ptr)
{
if(ptr!=NULL)
{
printf("%d ",ptr->data);
preorder(ptr->left);
preorder(ptr->right);
}
}
// To search an element from the tree
void search(node *root, int s)
{
node *ptr=root;
while(ptr!=NULL)
{
if(ptr->data==s)
{
printf("\n%d is found.",s);
return;
}
else
{
if(ptr->data>s)
ptr=ptr->left;
if(ptr->data<s)
ptr=ptr->right;
}
}
printf("\n%d is not present in a tree.",s);
}
0 Comments