#include #include using namespace std; // trees of strings struct node { string data; node * left, * right; node(string s) { data = s; left = NULL; right = NULL; } }; bool loop_search(node * p, string wanted) { while (p != NULL) { if (p->data == wanted) return true; if (wanted < p->data) p = p->left; else p = p->right; } return false; } bool rec_search(node * p, string wanted) { if (p == NULL) return false; if (p->data == wanted) return true; if (wanted < p->data) return rec_search(p->left, wanted); else return rec_search(p->right, wanted); } void BAD_insert(node * p, string toadd) { while (p != NULL) { if (p->data == toadd) return; if (toadd < p->data) { if (p->left == NULL) { p->left = new node(toadd); return; } else p = p->left; } else { if (p->right == NULL) { p->right = new node(toadd); return; } else p = p->right; } } } void loop_insert(node * & p, string toadd) { if (p == NULL) { p = new node(toadd); return; } node * temp = p; while (temp != NULL) { if (temp->data == toadd) return; if (toadd < temp->data) { if (temp->left == NULL) { temp->left = new node(toadd); return; } else temp = temp->left; } else { if (temp->right == NULL) { temp->right = new node(toadd); return; } else temp = temp->right; } } } int main() { node * tree = NULL; while (true) { string s; cout << "? "; cin >> s; bool b = loop_search(tree, s); if (b) cout << "Already there\n"; else { cout << "Adding it now\n"; loop_insert(tree, s); } } }