0% found this document useful (0 votes)
2 views

Binary Tree

The document describes a menu-driven program in C for performing operations on a Binary Search Tree (BST) of integers. It includes functions to create a BST, insert integers, and traverse the tree in inorder, preorder, and postorder. The main function facilitates user interaction for creating the BST and selecting traversal methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Binary Tree

The document describes a menu-driven program in C for performing operations on a Binary Search Tree (BST) of integers. It includes functions to create a BST, insert integers, and traverse the tree in inorder, preorder, and postorder. The main function facilitates user interaction for creating the BST and selecting traversal methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

7.

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....!");
}
}
}

You might also like