BST Operations

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

//Author Name:Huda Fathima

//registration number:200970020
//Program Description: program to perform bst operations
//date-of-creation:23-06-2021
#include<iostream>
using namespace std;

class node
{
public:
int data;
node *left;
node *right;
node(int d)
{
data=d;
left=NULL;
right=NULL;
}
node* insert(node *root,int value)
{
if(root==NULL)
{
return new node(value);
cout<<value<<" is added to Root Node";

}
else
{
node *cur;
if(value <= root->data){
cur=insert(root->left,value);
root->left=cur;
}
else {
cur=insert(root->right,value);
root->right=cur;
}
return root;
}
}
node* search(node *root,int key)
{
node *curr=root;
cout<<"Visiting Elements : ";
while(curr->data!=key) {
if(curr !=NULL) {
cout<<curr->data<<" ";
if(curr->data > key)
curr=curr->left;
else
curr=curr->right;
if(curr==NULL)
return NULL;
}
}
return curr;
}
void inorder(node *root)
{
if(root==NULL)
return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
void preorder(node *root)
{
if(root==NULL)
return;
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}

void postorder(node *root)


{
if(root==NULL)
return;
postorder(root->left);
postorder(root->right);
cout<<root->data<<" ";
}
};
int main()
{
node tree(0);
node *root=NULL;
int op,ch,val;
do
{
cout<<"\nBINARY SEARCH TREE OPERATIONS";
cout<<"\n1.Insert\t2.Search\t3.Inorder Traversal\n4.Preorder Traversal\t\t5.Postorder
Traversal\n6.Exit";
cout<<"\nEnter your choice : ";
cin>>ch;
switch(ch)
{
case 1:
cout<<"Enter the value to insert : ";
int ins;
cin>>ins;
root=tree.insert(root,ins);
cout<<ins<<" inserted";
break;
case 2: {
cout<<"Enter the value to search : ";
int key;
cin>>key;
node* find_node=tree.search(root,key);
if(find_node)
cout<<key<<" found";
else
cout<<key<<" not found";
}
break;
case 3:
cout<<"The Inorder traversal is : ";
tree.inorder(root);

break;
case 4:
cout<<"The Preorder traversal is : ";
tree.preorder(root);

break;
case 5:
cout<<"The Postorder traversal is : ";
tree.postorder(root);

break;

case 6: break;
}
cout<<"\nPress 1 to continue : ";
cin>>op;
}while(op==1);
return 0;
}

You might also like