头文件
BSTree.h
#ifndef __BSTREE_H__
#define __BSTREE_H__
#include<iostream>
using namespace std;
template<class Type>
class BSTree;
template<class Type>
class BSTNode
{
friend class BSTree<Type>;
public:
BSTNode():data(Type()),leftChild(NULL),rightChild(NULL)
{}
BSTNode(Type d,BSTNode<Type> *left = NULL,BSTNode<Type> *right = NULL):data(d),leftChild(left),rightChild(right)
{}
~BSTNode()
{}
public:
void SetData(Type d)
{
data = d;
}
Type GetData()const
{
return data;
}
private:
Type data;
BSTNode<Type> *leftChild;
BSTNode<Type> *rightChild;
};
template<class Type>
class BSTree
{
public:
BSTree() : root(NULL)
{}
BSTree(Type ar[],int n):root(NULL)
{
for(int i = 0;i<n;i++)
{
insert(ar[i]);
}
}
~BSTree()
{
//MakeEmpty();
}
public:
bool insert(Type &x)
{
return insert(root,x);
}
void sort()const
{
sort(root);
}
/////////////////////////////////////////////////////////////////
BSTNode<Type>* Max()const;
BSTNode<Type>* Min()const;
BSTNode<Type>* Find(Type &key)const;
BSTNode<Type>* Parent(BSTNode<Type> *p)const;
void MakeEmpty();
bool Copy(BSTree<Type> &t);//bst1.Copy(bst2)
BSTree<Type>& operator=(BSTree<Type> &t);//bst1 = bst2
bool remove(const Type &key)
{
return remove(root,key);
}
protected:
bool remove(BSTNode<Type> *&t,const Type &key)
{
if(key < t->data)
remove(t->leftChild,key);
else if(key > t->data)
remove(t->rightChild,key);
else
{
if(t->leftChild == NULL && t->rightChild == NULL)
{
delete t;
t = NULL;
}
else if(t->leftChild != NULL && t->rightChild == NULL)
{
BSTNode<Type> *tmp = t;
t = t->leftChild;
delete tmp;
}
else
{
BSTNode<Type> *tmp = t->rightChild;
while(tmp->rightChild != NULL)
{
tmp = tmp->rightChild;
}
t->data = tmp->data;
remove(t->rightChild,t->data);
}
return true;
}
}
void sort(BSTNode<Type> *t)const
{
if(t!=NULL)
{
sort(t->leftChild);
cout<<t->data<<" ";
sort(t->rightChild);
}
}
bool insert(BSTNode<Type> *&t,Type &x)
{
if(t == NULL)
{
t = new BSTNode<Type>(x);
return true;
}
else if(x < t->data)
insert(t->leftChild,x);
else if(x > t->data)
insert(t->rightChild,x);
else
return false;
}
private:
BSTNode<Type> *root;
};
#endif
源文件
BSTree.cpp
#include<iostream>
#include"BSTree.h"
using namespace std;
int main()
{
int ar[] = {53,78,65,17,87,9,81,45,23};
int n = sizeof(ar)/sizeof(int);
BSTree<int> bst(ar,n);
bst.sort();
/*
for(int i = 0;i<n;++i)
{
bst.insert(ar[i]);
}
*/
system("pause");
return 0;
}