-1

How can this BST class be better?

```
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
using namespace std;
template <class KeyType, class ValueType>
class BST
{
public:
BST(): mroot(0), mcount(0) {}
BST(BST const& tree) { *this = clone(tree.mroot); }
BST& operator=(BST const& tree)
{
if (this != &tree)
{
mroot = clone(tree.mroot);
mcount = tree.mcount;
}
return *this;
}
~BST() { remove_all(mroot); }
void add(KeyType key, ValueType value, bool at_root=false)
{
add(mroot, key, value, at_root);
++mcount;
}
void remove(KeyType key) { if (remove(mroot, key)) --mcount; }
bool exists(KeyType key) const { return find(mroot, key) != 0; }
ValueType value(KeyType key) const
{
node* found = find(mroot, key);
return found ? found->value : ValueType();
}
int count() const { return mcount; }
void print() const { print(mroot); }
private:
class node
{
public:
node(KeyType key, ValueType value, node* left, node* right)
: key(key), value(value), left(left), right(right) {}
public:
KeyType key;
ValueType value;
node* left;
node* right;
};
void rotate(node*& oldroot, node*& newroot, node*& swapsibling)
{
node* tmp = newroot;
newroot = swapsibling;
swapsibling = oldroot;
oldroot = tmp;
}
void add(node*& root, KeyType key, ValueType value, bool at_root=false)
{
if (!root)
root = new node(key, value, 0, 0);
else if (key < root->key)
{
add(root->left, key, value, at_root);
if (at_root)
rotate(root, root->left, root->left->right);
}
else
{
add(root->right, key, value, at_root);
if (at_root)
rotate(root, root->right, root->right->left);
}
}
bool remove(node*& root, KeyType key)
{
if (!root)
return false;
if (key == root->key)
{
if (!root->left && !root->right)
{
delete root;
root = 0;
return true;
}
else if (root->left)
rotate(root, root->left, root->left->right);
else
rotate(root, root->right, root->right->left);
}
if (key < root->key)
return remove(root->left, key);
else
return remove(root->right, key);
}
node *clone(node* root) const
{
if (!root)
return root;
node *curr = new node(root->key, root->value, 0, 0);
curr->left = clone(root->left);
curr->right = clone(root->right);
return curr;
}
node* find(node* root, KeyType key) const
{
if (!root || key == root->key)
return root;
else if (key < root->key)
return find(root->left, key);
else
return find(root->right, key);
}
void remove_all(node*& root)
{
if (!root)
return;
remove_all(root->right);
remove_all(root->left);
delete root;
}
void print(node* root, int depth=0) const
{
if (root)
{
print(root->right, depth + 1);
cout << setw(depth * 4) << "(" << root->key <<","<< root->value <<")" << endl;
print(root->left, depth + 1);
}
}
private:
node* mroot;
int mcount;
};
int main()
{
srand(unsigned(time(0)));
while (true)
{
system("CLS");
BST<int, int> tree;
for (int x = 0; x < 10; ++x)
tree.add(x, x, rand() % 2 != 0);
tree.print();
cout << "Hit ENTER to repeat..." << flush;
if (getch() != '\r')
{
cout << endl;
break;
}
}
}
```