You are on page 1of 3

/* Program to implement Binary Search Tree */

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>

class BinaryST
{
public:
struct node
{
int data;
node *left, *right;
}*root, *head;
public:
BinaryST();
node createBST(node root, int x);
void inorder(node root);
void postorder(node root);
void preorder(node root);

};

BinaryST::BinaryST()
{
head = NULL;
}

node BinaryST::creatBST(node temp, int x)


{
root = temp;
if(root == NULL)
{
root->data = x;
root->left = NULL;
root->right = NULL;

return root;
}
else
{
if(x < root->data)
root->left = createBST(root->left, x);
else if(x > root->data)
root->right = createBST(root->right, x);
else
cout<<"Duplicate elements cannot be inserted in Binary Search
Tree\n";
return root;
}
}

void BinaryST::inorder(node root)


{
if(root != NULL)
{
inorder(root->left);
cout<<root->data;
inorder(root->right);
}
}

void BinaryST::preorder(node root)


{
if(root != NULL)
{
cout<<root->data;
preorder(root->left);
preorder(root->right);
}
}

void BinaryST::postorder(node root)


{
if(root != NULL)
{
postorder(root->left);
postorder(root->right);
cout<<root->data;
}
}

void menu()
{
cout<<"1. Binay Search Tree Creation. \n";
cout<<"2. Traversing BST in Preorder. \n";
cout<<"3. Traversing BST in Inorder. \n";]
cout<<"4. Traversing BST in Postorder. \n";
cout<<"5. Exit out..... \n";
}

void main()
{
int ch;
char c = 'y';
BinaryST bstobj;
bstobj.root = NULL;
do
{
clrscr();
menu();
cout<<"Enter your choice: \n";
cin>>ch;
switch(ch)
{
case 1:
cout<<"Enter the element to be added to BST.\n";
int x;
root = bstobj.createBST(root, x);
break;
case 2:
cout<<"BST traversal using Preorder Technique. \n";
bstobj.preorder(root);
break;
case 3:
cout<<"BST traversal using Inorder Technique. \n";
bstobj.inorder(root);
break;
case 4:
cout<<"BST traversal using Postorder Technique. \n";
bstobj.postorder(root);
break;
case 5:
exit(1);
break;
}
cout<<"Do you want to continue? (y-yes | n-no). \n";
cin>>c;
}while(c == 'n');
getch();
}

You might also like