Write a menu driven program to implement binary tree using linked list and
different traversals.
#include <stdio.h>
#include <stdlib.h>
struct Binary
{
int info;
struct Binary *L;
struct Binary *R;
};
typedef struct Binary NODE;
NODE *node;
NODE* makeTree(NODE *node, int info)
{
if (node == NULL)
{
NODE *temp;
temp= (NODE*)malloc(sizeof(NODE));
temp->info = info;
temp->L = temp->R = NULL;
return temp;
}
if (info < (node->info))
{
node->L = makeTree(node->L, info);
}
else if (info > node->info)
{
node -> R = makeTree(node->R, info);
}
return node;
}
NODE* find(NODE *node, int info)
{
if(node == NULL)
printf("\nElement not found");
else if(info < node->info)
{
node->L=find(node->L, info);
}
else if(info > node->info)
{
node->R=find(node->R, info);
}
else
printf("\nElement found is: %d", node->info);
return node;
}
void inorder(NODE *node)
{
if(node != NULL)
{
inorder(node->L);
printf("%d\t", node->info);
inorder(node->R);
}
}
void preorder(NODE *node)
{
if(node != NULL)
{
printf("%d\t", node->info);
preorder(node->L);
preorder(node->R);
}
}
void postorder(NODE *node)
{
if(node != NULL)
{
postorder(node->L);
postorder(node->R);
printf("%d\t", node->info);
}
}
NODE* getmin(NODE *node)
{
if(node==NULL)
{
return NULL;
}
if(node->L)
return getmin(node->L);
else
return node;
}
NODE* delete(NODE *node, int info)
{
NODE *temp;
if(node == NULL)
{
printf("\nElement not found");
}
else if(info < node->info)
{
node->L = delete(node->L, info);
}
else if(info > node->info)
{
node->R = delete(node->R, info);
}
else
{
if(node->R && node->L)
{
temp = getmin(node->R);
node -> info = temp->info;
node -> R = delete(node->R,temp->info);
}
else
{
temp = node;
if(node->L == NULL)
node = node->R;
else if(node->R == NULL)
node = node->L;
free(temp);
}
}
return node;
}
void main()
{
int info, option, i, n;
NODE *bottom=NULL;
while (1)
{
printf("\n1.Insertion");
printf("\n2.Search");
printf("\n3.Delete");
printf("\n4.Inorder\n5.Preorder\n6.Postorder\n7.Exit");
printf("\nEnter your option: ");
scanf("%d", &option);
switch (option)
{
case 1:
printf("\nEnter N value: " );
scanf("%d", &n);
printf("\ninput the values to create Tree\n");
for(i=0; i<n; i++)
{
scanf("%d", &info);
bottom=makeTree(bottom, info);
}
break;
case 2:
printf("\nEnter the element to search: ");
scanf("%d", &info);
bottom=find(bottom, info);
break;
case 3:
printf("\nEnter the element to delete: ");
scanf("%d", &info);
bottom=delete(bottom, info);
break;
case 4:
printf("\nInorder Traversal: \n");
inorder(bottom);
break;
case 5:
printf("\nPreorder Traversal: \n");
preorder(bottom);
break;
case 6:
printf("\nPostorder Traversal: \n");
postorder(bottom);
break;
case 7: exit(0);
default:printf("\nWrong option");
break;
}
}
}
Comments
Leave a comment