您的位置:首页 > 其它

BST二叉搜索树的实现

2008-12-24 12:49 435 查看
编译环境:vc++6.0

#include <iostream>
using namespace std;

template<class T>
class BST;

template<class T>
class node
{
friend void Iterator( node<T>* r);
friend class BST<T>;
private:
T data;
node<T> *lp,*rp; //左右孩子指针
public:
node(){lp=rp=NULL;} //初始化
node(T d,node<T> *l=NULL,node<T> *r=NULL):data(d),lp(l),rp(r){}
T getdata(){return data;}
};

template<class T>
class BST
{
friend void Iterator( node<T>* r);
private:
node<T> *root; //树根指针
int value;
node<T>* find(const T& x,node<T> *r)
{
if(r==NULL)
return NULL;
if(x<r->data)
return find(x,r->lp);
else if(x>r->data)
return find(x,r->rp);
else return r;
}
void insert(const T& x,node<T> *&root)
{
if(root==NULL)
{
root=new node<T>(x);
cout<<"have inserted "<<x<<endl;
}
else if(x<root->data)
insert(x,root->lp);
else if(x>root->data)
insert(x,root->rp);
else
cout<<"the data "<<x<<" has already inserted!"<<endl;
}

node<T>*& min(node<T>* &r)
{
if(r->lp!=NULL)
return min(r->lp);

else return r;
}

void remove(const T& x,node<T> * &root)
{
if(root==NULL)
{
cout<<"have not this data "<<x<<endl;
return;
}
else if(x<root->data) //在左子树中查找
remove(x,root->lp);
else if(x>root->data) //在右子树中查找
remove(x,root->rp);
//找到x值
else if(root->lp==NULL&&root->rp==NULL) //删除的节点为叶子节点
{
node<T> *q=root;
root=NULL;
delete q;
}
else if(root->lp==NULL) //删除的节点左子树为空
{
node<T> *q=root;
root=root->rp;
delete q;
}
else if(root->rp==NULL) //删除的节点右子树为空
{
node<T> *q=root;
root=root->lp;
delete q;
}
else //左右子树都不为空,用该节点的直接先驱节点去替代,然后删除直接前驱节点.
{ node<T> * &p=min(root->rp);
root->data=p->getdata();
remove(root->data,p);
}
}
public:
BST(int v)
{
root=NULL;
cout<<"input the element when "<<v<<" stop"<<endl;
T x;
cin>>x;
while(x!=v)
{
insert(x,root);
cin>>x;
}
}
node<T>* find(const T&x)
{
return find(x,root);
}

void insert(const T& x)
{
if(root==NULL)
{ root->data=x;cout<<"have inserted "<<x<<endl;}
else insert(x,root);
}
node<T> *& min()
{
if(root==NULL)
return NULL;
return min(root);
}

void remove(const T& x) //if lp is null and rp is null,remove it
{ //else if lp is null,replace it with its rp;
if(root==NULL) //if they are both not null,replace it with the smallest data of rp
{
cout<<"it is null"<<endl;return ;
}
remove(x,root);
}
node<T>* getroot()
{
return root;
}
};

template<class T>
void Iterator( node<T>* r)// 中序遍历
{
while(r!=NULL)
{ cout<<r->getdata()<<" ";
Iterator(r->lp);
Iterator(r->rp);
return;
}
}

int main()
{
BST<int> bst(100);
bst.insert(2);
bst.insert(3);
cout<<(bst.find(2))->getdata()<<endl;
cout<<"the tree is"<<endl;
Iterator( bst.getroot());
bst.remove(2);
bst.remove(7);
bst.remove(3);
cout<<"/nthe tree is"<<endl;
Iterator( bst.getroot());
cin.get();

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: