树
2018-01-03 12:53 彬少608 阅读(148) 评论(0) 收藏 举报template<typename Object,typename Comparator=less<Object>>
class BinarySearchTree{
public:
BinarySearchTree();
~BinarySearchTree();
BinarySearchTree(const BinarySearchTree &rhs);
const BinarySearchTree &operator=(const BinarySearchTree &rhs);
const Object &findMin() const;
const Object &findMax() const;
bool contains(const Object &x) const;
bool isEmpty() const;
void printTree() const;
void makeEmpty();
void insert(const Object &x) const;
void move(const Object &x) const;
private:
struct BinaryNode(){
Object element;
BinaryNode *left;
BinaryNode *right;
BinaryNode(const Object &e,BinaryNode *lt,BinaryNode *rt):element(e),left(lt),right(rt){}
}
BinaryNode *root;
Comparator lsLessThan;
void insert(const Object &x,BinaryNode* &t) const;
void remove(const Object &x,BinaryNode* &t) const;
BinaryNode* findMin(BinaryNode *t) const;
BinaryNode* findMax(BinaryNode *t) const;
bool contains(const Object &x,BinaryNode *t) const;
void makeEmpty(BinaryNode * &t);
void printTree(BinaryNode *t) const;
BinaryNode *clone(BinaryNode *t) const;
bool contains(const Object &x) const {return contains(x,root);}
void insert(const Object &x) { insert(x,root);}
void remove(const Object &x) { move(x,root);}
bool contains(const Object &x,BinaryNode *t) const{
if(t==NULL)
return false;
else if(isLessThan(x,t->element))
return contains(x,t->left);
else if(isLessThan(t->element,x))
return contains(x,t->right);
else
return true;
}
void insert(const Object &x,BinaryNode * &t){
if(t==NULL)
t=new BinaryNode(x,NULL,NULL);
else if(x<t->element)
insert(x,t->left);
else if(x>t=>element)
insert(x,t->right);
}
void remove(const Object &x,BinaryNode * &t){
if(t==NULL)
return;
if(x<t->element)
remove(x,t->left);
else if(x>t->element)
remove(x,t->right);
else if(t->left!=NULL && t->right!=NULL)
t->element=findMin(t->right)->element;
remove(t->element,t->right);
else
BinaryNode *old=t;
t=(t->left!=NULL)?t->left : t->right;
delete old;
}
~BinarySearchTree(){makeEmpty();}
void makeEmpty(BinaryNode * &t){
if(t!=NULL)
makeEmpty(t->left);
makeEmpty(t->right);
delete t;
t=NULL;
}
const BinarySearchTree &operator=(const BinarySearchTree &rhs){
if(this!=&rhs)
makeEmpty();
root=clone(rhs.root);
return *this;
}
BinaryNode *clone(BinaryNode *t) const{
if(t==NULL)
return NULL;
return new BinaryNode(t->element,clone(t->left),clone(t->right));
}
};
浙公网安备 33010602011771号