BinarySearchTree类,只是一个操作类,提供操作函数,不提供存储。
#include <iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
class BinarySearchTree;
class BinaryNode
{
public :
int element;
BinaryNode *leftChild;
BinaryNode *rightChild;
BinaryNode(int theElement,BinaryNode *lt,BinaryNode *rt)
:element(theElement),leftChild(lt),rightChild(rt){};
friend class BinarySearchTree;
};
class BinarySearchTree
{ public:
BinaryNode *root;
BinarySearchTree(BinaryNode *rt){root=rt;}
BinaryNode* findMax(BinaryNode *t)const;
BinaryNode* findMin(BinaryNode *t)const;
BinaryNode* find(int x,BinaryNode * t)const;
void insert(int x,BinaryNode * & t);
void remove(int x,BinaryNode * & t);
void removeMin(BinaryNode * & t);
};
BinaryNode* BinarySearchTree::find(int x,BinaryNode* t)const
{
while(t!=NULL)
{ if(t->element==x) return t; //自己加的
if(x<t->element) t=t->leftChild;
else if(x>t->element) t=t->rightChild;
}
return NULL;
}
BinaryNode *BinarySearchTree::findMax(BinaryNode* t)const
{ if(t!=NULL)
while(t->rightChild!=NULL) t=t->rightChild;
return t;
}
BinaryNode *BinarySearchTree::findMin(BinaryNode* t)const
{ if(t!=NULL)
while(t->leftChild!=NULL) t=t->leftChild;
return t;
}
void BinarySearchTree::insert(int x,BinaryNode* &t)
{ if(t==NULL)
t=new BinaryNode(x,NULL,NULL);
else if(x<t->element) insert(x,t->leftChild);
else insert(x,t->rightChild);//允许重复
}
void BinarySearchTree::removeMin(BinaryNode* &t)
{ if(t==NULL)
{ cout<<"removeMinERROR";
return;
}
else{ if(t->leftChild!=NULL)
removeMin(t->leftChild);
else{ BinaryNode* tmp;
tmp=t;
t=t->rightChild;
delete tmp;
}
}
}
void BinarySearchTree::remove(int x,BinaryNode* &t)
{ if(t==NULL) {cout<<"removeERROR";return;}
if(x<t->element)remove(x,t->leftChild);
else if(x>t->element) remove(x,t->rightChild);
else{ if(t->leftChild!=NULL && t->rightChild!=NULL)
{ t->element=findMin(t->rightChild)->element;
removeMin(t->rightChild);
}
else{ BinaryNode* tmp=t;
t=(t->leftChild!=NULL)?t->leftChild:t->rightChild;
delete tmp;
}
}
}
void viewTree(BinaryNode* t)//
{ if(t==NULL) return;
else{ if(t->leftChild!=NULL) viewTree(t->leftChild);
cout<<t->element<<" ";
if(t->rightChild!=NULL) viewTree(t->rightChild);
}
}
int main()
{ int n;
cin>>n;
srand((unsigned)time(0));
BinarySearchTree bst(NULL);
BinaryNode* r=NULL;
for(int i=1;i<=n;i++)
{ int a=rand()%32000;
cout<<i<<" "<<a<<"insert"<<endl;
bst.insert(a,r);
}
viewTree(r);
cout<<endl;
while(1)
{
cout<<"find: ";
int x;
cin>>x;
if(bst.find(x,r)) cout<<"find it"<<endl ;
else cout<<"I can not find it";
cout<<endl<<"Insert ";
cin>>x;
bst.insert(x,r);
cout<<endl<<"Delete ";
cin>>x;
bst.remove(x,r);
}
}