Sa3 2101053 Dsa6
Sa3 2101053 Dsa6
- 3
INPUT
#include<iostream>
#include<string>
using namespace std;
class
node{ public:
string key;
string value;
node*left;
node*right;
class
BST{ public:
int n;
node*root;
BST(){
root = NULL;
}
void createTree(){
node*temp;
cout<<"Enter the number of elements:";
cin>>n;
for(int i=0; i<n; i++)
{ string key, value;
cout<<"Enter the key and value (separated by space): ";
cin>>key>>value;
temp = createNode(key, value);
if(root == NULL){
root = temp;
}
else{
insertNode(root, temp);
}
}
}
void inorder(node*root){
if(root == NULL){
return;
}
inorder(root->left);
cout<< "(" << root->key << ", " << root->value << ") ";
inorder(root->right);
}
return root;
}
};
int main(){
BST b;
string key1, key2, value1;
b.createTree();
cout << endl << "The tree generated is:";
b.inorder(b.root);
cout << endl;
{ int
choice;
switch(choice)
{ case 1:
cout<<"Enter key and value to insert: ";
cin>>key1>>value1;
b.addnode(key1, value1);
break;
case 2:
cout<<"Enter the key to find: ";
cin>>key1;
b.search(b.root, key1);
break;
case 3:
cout<<"Enter the key to delete: ";
cin>>key2;
b.deleteNode(b.root, key2);
b.inorder(b.root);
cout<<endl;
break;
case 4:
cout<<"Program closed."<<endl;
return 0;
default:
break;
}
}
}
Output:
The tree generated is:(Baleno, Mahesh) (Compass, Rushi) (Nano, Tushar) (Nexon, Shriram) (Swift,
Pawan)
-------------------Menu-------------------
1. Add new node.
2. Search an element in the tree.
3. Delete an element from the tree.
4. Exit program.