void insert(string key, Object o); Object lookup(string key); void remove(string key);
class BinarySearchTree
{
struct TreeNode
{
string key;
Object info;
TreeNode * left, * right;
TreeNode(string k, Object in, TreeNode * l, TreeNode * r)
{
key = k; info = in; left = l; right = r;
}
static TreeNode * find(string k, TreeNode * t);
static TreeNode * insert(string k, Object in, TreeNode * t);
static TreeNode * remove(string k, TreeNode * t);
static void destruct(TreeNode * t);
};
TreeNode * root;
public:
BinarySearchTree();
void insert(string key, Object info);
Object lookup(string key);
void remove(string key);
~BinarySearchTree();
};
void preorder(TreeNode * root)
{
if (root != null)
{
cout << root->info;
preorder(root->left);
preorder(root->right);
}
}
void inorder(TreeNode * root)
{
if (root != null)
{
inorder(root->left);
cout << root->info;
inorder(root->right);
}
}
void postorder(TreeNode * root)
{
if (root != null)
{
postorder(root->left);
postorder(root->right);
cout << root->info;
}
}
// returns the last node to the right of node t
template
<typename T>
void swap(T & A, T & B)
{
T X = A;
A = B;
B = X;
}
void swapKeyAndInfo(TreeNode * t1, TreeNode * t2);
{
swap(t1->key, t2->key);
swap(t1->info, t2->info);
}
TreeNode * rightMost(TreeNode * t)
{
while ( t->right )
t = t->right;
return t;
}
TreeNode * removeThisNode(TreeNode *t)
{ // of course, we must deal with deleting removed node
if (!t->left)
return t->right;
else if (!t->right)
return t->left;
else // the hard case, it has two children
{
TreeNode * rightMostOfLeft = rightMost(t->left);
swapKeyAndInfo(t, rightMostOfLeft);
t->left = remove(key, t->left);
}
}
BinarySearchTree::TreeNode *
BinarySearchTree :: remove(string key, TreeNode * t)
{
if (t == 0)
return 0;
if (key < t->key)
t->left = remove(key, t->left);
else if (key > t->key)
t->right = remove(key, t->right);
else
t = removeThisNode(t);
return t;
}