- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- template<typename object>
- class less
- {
- public:
- bool operator()(object lhs,object rhs)
- {
- return lhs < rhs;
- }
- };
- template<typename object,typename comparator = less<object> >
- class BinarySearchTree
- {
- struct BinaryNode
- {
- object element;
- BinaryNode* left;
- BinaryNode* right;
- };
- public:
- BinarySearchTree()
- {
- }
- ~BinarySearchTree()
- {
- //todo:
- }
- BinaryNode* findMin() const;
- BinaryNode* findMax() const;
- bool contains(const object& x) const;
- void printTree(ostream& out = cout);
- private:
- BinaryNode* root;
- comparator isLessThan;
- bool contains(const object& x,BinaryNode* t) const;
- BinaryNode* findMin(BinaryNode* t) const
- {
- if (t == NULL)
- {
- return NULL;
- }
- if (t->left == NULL)
- {
- return t;
- }
- return findMin(t->left);
- }
- BinaryNode* findMax(BinaryNode* t) const
- {
- if (t == NULL)
- {
- return NULL;
- }
- while(t->right != NULL)
- {
- t = t->right;
- }
- return t;
- }
- void insert(const object& x,BinaryNode* t)
- {
- if (t == NULL)
- {
- t = new BinaryNode;
- t->element = x;
- t->left = NULL;
- t->right = NULL;
- }
- else if (isLessThan(x,t->element))
- {
- insert(x,t->left);
- }
- else if (isLessThan(t->element, x))
- {
- insert(x,t->right);
- }
- }
- void remove(const object& x,BinaryNode* t)
- {
- if (t == NULL)
- return;
- if (isLessThan(x,t->element))
- {
- remove(x,t->left);
- }
- else if (isLessThan(t->element,x))
- {
- remove(x,t->element);
- }
- else if (t->left != NULL && t->right != NULL)
- {
- t->element = findMin(t->right)->element;
- remove(t->element, t->right);
- }
- else
- {
- BinaryNode* p = t;
- t = (t->left !=NULL) ? t->left : t->right;
- delete p;
- }
- }
- void printTree(BinaryNode* t,ostream& out)
- {
- if (t != NULL)
- {
- printTree(t->left, out);
- out << t->element << endl;
- printTree(t->right, out);
- }
- }
- void height(BinaryNode* t)
- {
- if (t == NULL)
- return 0;
- if (t->left != NULL || t->right != NULL)
- return 1 + max(height(t->left),height(t->right));
- }
- };
- template<typename object,typename comparator>
- bool BinarySearchTree<object,comparator>::contains(const object& x,BinaryNode* t) const
- {
- if (t == NULL)
- {
- return false;
- }
- if (isLessThan(x,t->element))
- {
- return contains(x,t->left);
- }
- else if(isLessThan(t->element,x))
- {
- return contains(x,t->right);
- }
- else
- {
- return true;
- }
- return false;
- }
- template<typename object, typename comparator>
- bool BinarySearchTree<object, comparator>::contains(const object& x) const
- {
- return contains(x,t);
- }
- template<typename object, typename comparator>
- void BinarySearchTree<object, comparator>::printTree(ostream& out)
- {
- if (t == NULL)
- {
- out << "empty tree" << endl;
- return;
- }
- printTree(t,out);
- }
未完待续。