Binary Tree
Binary Tree
Menu driven program for the following operations on Binary Search Tree (BST) of
Integers (a) Create a BST of N Integers
(b) Traverse the BST in Inorder, Preorder and Post Order
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct BST
{
int data;
struct BST*left;
struct BST*right;
};
struct BST*insert(struct BST*ptr,int data)
{
if(ptr==NULL)
{
struct BST*temp;
temp=(struct BST*)malloc(sizeof(struct BST));
temp->data=data;
temp->left=temp->right=NULL;
return temp;
}
if(data>(ptr->data))
{
ptr->right=insert(ptr->right,data);
}
else if(data<(ptr->data))
{
ptr->left=insert(ptr->left,data);
}
return ptr;
}
void inOrder(struct BST*ptr)
{
if(ptr!=NULL)
{
inOrder(ptr->left);
printf("%d\t",ptr->data);
inOrder(ptr->right);
}
}
void preOrder(struct BST*ptr)
{
if(ptr!=NULL)
{
printf("%d\t",ptr->data);
preOrder(ptr->left);
preOrder(ptr->right);
}
}
void postOrder(struct BST*ptr)
{
if(ptr!=NULL)
{
postOrder(ptr->left);
postOrder(ptr->right);
printf("%d\t",ptr->data);
}
}
void main()
{
struct BST* root=NULL,*temp;
int ch,n,a,i;
clrscr();
printf("\n****Creation of Binary Search tree****");
printf("\n Enter the total number of BST:");
scanf("%d",&n);
printf("Enter %d element to insert:\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a);
root=insert(root,a);
}
while(1)
{
printf("\n1.inOrder \n2.preOrder \n3.postOrder \n4.Exit");
printf("\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("inOrder traversing is:");
inOrder(root);
break;
case 2:printf("preOrder traversing is:");
preOrder(root);
break;
case 3:printf("postOrder traversing is:");
postOrder(root);
break;
case 4:exit(0);
break;
default:printf("\n Invalid choice....!");
}
}
}