/* * binordtree.cpp * * Created on: 28.11.2012 * Author: trifon */ #include "tree.cpp" template struct Pair { K key; V value; }; template ostream& operator<<(ostream& os, Pair const& pair) { os << '[' << pair.key << ',' << pair.value << ']'; return os; } template class BinOrdTree : public BinTree > { typedef Pair T; private: void createTree(T const&, BinTree&, BinTree& ) {} node* minTree(node*& n) { node** p = &n; while ((*p)->left != NULL) { p = &((*p)->left); } // (*p)->left == NULL node* result = *p; *p = (*p)->right; return result; } node** findNode(K const& key, node*& start) { node** n = &start; while(*n && (*n)->inf.key != key) { if (key < (*n)->inf.key) n = &((*n)->left); else n = &((*n)->right); } // *n == NULL || *n->inf.key == key return n; } public: V* search(K const& key) const { BinTreeIterator it = this->iterator(); while (it && (*it).key != key) { if (key < (*it).key) it = ++it; else it = it++; } // !it || *it.key == key if (!it) return NULL; return &((*it).value); } bool insert(K const& key, V const& value) { node** n = findNode(key, this->root); if (*n == NULL) { *n = new node; T pair = { key, value }; (*n)->inf = pair; (*n)->left = (*n)->right = NULL; return true; } return false; } bool remove(K const& key) { node** n = findNode(key, this->root); if (*n == NULL) return false; node* p = *n; if ((*n)->left == NULL) *n = (*n)->right; else if ((*n)->right == NULL) *n = (*n)->left; else { // заменяме *n с най-малкия елемент node* q = minTree((*n)->right); *n = q; q->left = p->left; q->right = p->right; } delete p; return true; } };