struct BiNode
{
int data;
BiNode *lchild, *rchild;
};
class BiSortTree
{
public:
BiSortTree(int a[ ], int n);
~ BiSortTree( )
{
Release(root);
}
void InOrder( )
{
InOrder(root);
}
BiNode *InsertBST(int x)
{
return InsertBST(root, x);
}
BiNode *SearchBST(int k)
{
return SearchBST(root, k);
}
void DeleteBST(BiNode *p, BiNode *f );
private:
void Release(BiNode *bt);
BiNode *InsertBST(BiNode *bt, int x);
BiNode *SearchBST(BiNode *bt, int k);
void InOrder(BiNode *bt);
BiNode *root;
};
void BiSortTree :: InOrder(BiNode *bt)
{
if (bt == NULL)
return;
else
{
InOrder(bt->lchild);
cout << bt->data << " ";
InOrder(bt->rchild);
}
cout<<endl;
}
BiNode * BiSortTree :: SearchBST(BiNode *bt, int k)
{
if (bt == NULL)
return NULL;
if (bt->data == k)
return bt;
else if (bt->data > k)
return SearchBST(bt->lchild, k);
else
return SearchBST(bt->rchild, k);
}
BiNode *BiSortTree::InsertBST(BiNode *bt, int x)
{
if (bt == NULL)
{
BiNode *s = new BiNode;
s->data = x;
s->lchild = NULL;
s->rchild = NULL;
bt = s;
return bt;
}
else if (bt->data > x)
bt->lchild = InsertBST(bt->lchild, x);
else
bt->rchild = InsertBST(bt->rchild, x);
}
BiSortTree::BiSortTree(int a[ ], int n)
{
root = NULL;
for (int i = 0; i < n; i++)
root = InsertBST(root, a[i]);
}
void BiSortTree::DeleteBST(BiNode *p, BiNode *f )
{
if ((p->lchild == NULL) && (p->rchild == NULL))
{
f->lchild = NULL;
delete p;
return;
}
if (p->rchild == NULL)
{
f->lchild = p->lchild;
delete p;
return;
}
if (p->lchild == NULL)
{
f->lchild = p->rchild;
delete p;
return;
}
BiNode *par = p, *s = p->rchild;
while (s->lchild != NULL)
{
par = s;
s = s->lchild;
}
p->data = s->data;
if (par == p)
par->rchild = s->rchild;
else
par->lchild = s->rchild;
delete s;
}
void BiSortTree :: Release(BiNode *bt)
{
if (bt == NULL)
return;
else
{
Release(bt->lchild);
Release(bt->rchild);
delete bt;
}
}