Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- #include <cmath>
- #include <conio.h>
- using namespace std;
- struct Node {
- string key, value;
- Node *right = NULL, *left = NULL;
- Node(string a, string b) : key(a), value(b) {}
- };
- Node** treeSearch(Node** tree, string key) {
- if (*tree == NULL || (*tree) -> key == key) return tree;
- if (key > (*tree) -> key) return treeSearch(&((*tree) -> right), key);
- return treeSearch(&((*tree) -> left), key);
- }
- void treeInsert(Node** tree, string key, string value) {
- if (*tree == NULL) { *tree = new Node(key, value); return; }
- if ((*tree) -> key > key) { treeInsert(&((*tree) -> left), key, value); return; }
- treeInsert(&((*tree) -> right), key, value);
- }
- Node** treeMin(Node** tree) {
- if ((*tree) -> left == NULL) return tree;
- return treeMin(&((*tree) -> left));
- }
- void treeDelete(Node** tree) {
- if ((*tree) -> left && (*tree) -> right) {
- Node** p = treeMin(&((*tree) -> right));
- (*tree) -> key = (*p) -> key;
- (*tree) -> value = (*p) -> value;
- treeDelete(p);
- return;
- }
- Node* p;
- if ((*tree) -> left || (*tree) -> right) {
- if ((*tree) -> left) {
- p = (*tree) -> left;
- **tree = *((*tree) -> left);
- } else {
- p = (*tree) -> right;
- **tree = *((*tree) -> right);
- }
- delete p;
- return;
- }
- delete *tree;
- *tree = NULL;
- }
- void treePrint(Node* tree) {
- if (tree == NULL) return;
- treePrint(tree -> left);
- cout << tree -> key << ": " << tree -> value << endl;
- treePrint(tree -> right);
- }
- int main() {
- string command, surn, phone;
- Node* tree = NULL;
- while (1) {
- system("CLS");
- cout << "===Telephone directory based on binary search tree===" << endl << endl;
- cout << "add 'surname' 'phone' - add new contact" << endl;
- cout << "remove 'surname' - remove contact" << endl;
- cout << "search 'surname' - search contact" << endl;
- cout << "print - print all contacts" << endl;
- cout << "exit - close program" << endl;
- cout << endl << "<- ";
- cin.clear();
- cin >> command;
- if (command == "exit") break;
- if (command == "print") {
- cout << endl << "All contacts:" << endl;
- treePrint(tree);
- if (tree == NULL) cout << "empty" << endl;
- }
- if (command == "search") {
- cin.clear();
- cin >> surn;
- Node* p = *treeSearch(&tree, surn);
- if (p) cout << endl << p -> key << ": " << p -> value << endl;
- else cout << endl << "there is not" << endl;
- }
- if (command == "remove") {
- cin.clear();
- cin >> surn;
- Node** p = treeSearch(&tree, surn);
- if (*p) {
- treeDelete(p);
- cout << endl << "Removed" << endl;
- } else cout << endl << "there is not" << endl;
- }
- if (command == "add") {
- cin.clear();
- cin >> surn >> phone;
- if (*treeSearch(&tree, surn) == NULL) {
- treeInsert(&tree, surn, phone);
- cout << endl << "Aded" << endl;
- } else cout << endl << "already aded" << endl;
- }
- getch();
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment