1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
#ifndef BSTree_H
#define BSTree_H
#include "BTree.h"
#include<iostream>
#include<stdlib.h>
using namespace std;
template <class ItemType>
class BSTree: public BTree<ItemType>
{
private:
typedef NodeType<ItemType> * TreePtr;
TreePtr Tree;
void R_Insert(TreePtr &, ItemType x, int=0, int=0);
bool R_Search(TreePtr, ItemType);
bool R_Delete(TreePtr &,ItemType);
public:
BSTree(){Tree = NULL;};
virtual void Insert(ItemType x){R_Insert(Tree, x);};
bool Search(ItemType x){return R_Search(Tree, x);};
bool Delete(ItemType x){return R_Delete(Tree, x);};
~BSTree();
};
template<class ItemType>
bool BSTree<ItemType>::R_Search(TreePtr t,ItemType x)
{
if(t==NULL)
return 0;
else if(t->item==x)
return 1;
else if(x<t->item)
return R_Search(t->Lt,x);
else
return R_Search(t->Rt,x);
}
template<class ItemType>
void BSTree<ItemType>::R_Insert(TreePtr &t,ItemType x, int lev,int bal)
{
if(t==NULL)
t= new NodeType<ItemType>(x,lev);
else if(x<t->item)
R_Insert(t->Lt,x,lev+1,bal);
else
R_Insert(t->Rt,x,lev+1,bal);
}
template<class ItemType>
bool BSTree<ItemType>::R_Delete(TreePtr &t,ItemType x)
{
TreePtr delnode,parent,child;
if(t==NULL)
return 0;
else if(x<t->item)
return R_Delete(t->Lt,x);
else if(x>t->item)
return R_Delete(t->Rt,x);
else
{
if((t->Lt==NULL)&&(t->Rt==NULL))
{
delete t;
t=NULL;
}
else if(t->Lt==NULL)
{
delnode=t;
t=t->Rt;
delete delnode;
}
else if(t->Rt==NULL)
{
delnode=t;
t=t->Lt;
delete delnode;
}
else
{
parent=t;
child=t->Rt;
if(child->Lt==NULL)
{
parent->item=child->item;
parent->Rt=child->Rt;
delete child;
return 0;
}
else
{
while(child->Lt!=NULL)
{
parent=child;
child=child->Lt;
t->item=child->item;
parent->Lt=child->Lt;
delete child;
return 1;
}
}
}
}
}
template<class ItemType>
BSTree<ItemType>::~BSTree()
{
TreePtr t;
delete t;
//BTree<ItemType>::~BTree();
}
//BSTree<int>BST;
#endif
| |