您的位置:首页 > 其它

二叉查找树 BinarySearchTree 的实现

2010-11-06 00:06 796 查看
header.h

template<class type>
class BinarySearchTree
{
private:
struct node
{
type data;
node *left;
node *right;
node(type a,node*lt=NULL,node *rt=NULL){data=a;left=lt;right=rt;}
};
node *root;
bool find(type x,node *t);
void insert(type x,node *&t);
void remove(type x,node *&t);
public:
BinarySearchTree(node *t=NULL){root=t;}
bool find(type x);
void insert(type x);
void remove(type x);
void makeEmpty(node *&root);
~BinarySearchTree(){makeEmpty(root);}
};
//==================================
template<class type>
bool BinarySearchTree<type>::find(type x)
{
return find(x,root);
}
template<class type>
bool BinarySearchTree<type>::find(type x,node *t)
{
if(t==NULL)	return false;
else if(x>t->data)	return find(x,t->right);
else if(x<t->data)	return find(x,t->left);
else return true;
}
//==================================
template<class type>
void BinarySearchTree<type>::insert(type x)
{
insert(x,root);
}
template<class type>
void BinarySearchTree<type>::insert(type x,node *&t)
{
if(t==NULL){t=new node(x); return;}
else if(x<t->data)	insert(x,t->left);
else if(x>t->data)	insert(x,t->right);
}
//==================================
template<class type>
void BinarySearchTree<type>::remove(type x)
{
remove(x,root);
}
template<class type>
void BinarySearchTree<type>::remove(type x,node *&t)
{
if(t==NULL){cout<<x<<" doesn't exist!"<<endl; return;}
if(x<t->data)		remove(x,t->left);
else if(x>t->data)	remove(x,t->right);
else if(t->left!=NULL && t->right!=NULL)
{
node *p=t->right;
while(p->left!=NULL)	p=p->left;
t->data=p->data;
remove(t->data,t->right);
}
else
{
node* p=t;
t=(t->left!=NULL)?t->left:t->right;
delete p;
}
}
//==================================
template<class type>
void BinarySearchTree<type>::makeEmpty(node *&root)
{
if(root==NULL)	return;
else if(root->left==NULL && root->right==NULL)
delete root;
else {	makeEmpty(root->left);	makeEmpty(root->right);}
}


BST.h

#include <iostream>
#include "header.h"
using namespace std;
int main()
{
int i=0;
int a[]={10,8,6,21,87,56,4,0,11,3,22,7,5,34,1,2,9};
BinarySearchTree<int> bst;
int len=sizeof(a)/sizeof(int);
for(i=0;i<len;i++)
bst.insert(a[i]);
cout<<"find 2 is "<<(bst.find(2)?"true":"false")<<endl;
bst.remove(2);
cout<<"after remove 2,find 2 is "<<(bst.find(2)?"true":"false")<<endl;
cout<<"find 3 is "<<(bst.find(3)?"true":"false")<<endl;
bst.remove(3);
cout<<"after remove 3,find 3 is "<<(bst.find(2)?"true":"false")<<endl;
bst.remove(123);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  insert null delete struct
相关文章推荐