二叉排序树代码实现

struct BiNode
{
    int data;
    BiNode *lchild, *rchild;
};
class BiSortTree
{
public:
    BiSortTree(int a[ ], int n); //建立查找集合a[n]的二叉排序树
    ~ BiSortTree( )
    {
        Release(root);    //析构函数,同二叉链表的析构函数
    }
    void InOrder( )
    {
        InOrder(root);   //中序遍历二叉树
    }
    BiNode *InsertBST(int x)
    {
        return InsertBST(root, x);   //插入x
    }
    BiNode *SearchBST(int k)
    {
        return SearchBST(root, k);   //查找值为k的结点
    }
    void DeleteBST(BiNode *p, BiNode *f ); //删除f的左孩子p
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); //前序递归遍历bt的左子树
        cout << bt->data << " "; //访问根结点bt的数据域
        InOrder(bt->rchild); //前序递归遍历bt的右子树
    }
    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))   //p为叶子
    {
        f->lchild = NULL;
        delete p;
        return;
    }
    if (p->rchild == NULL)   //p只有左子树
    {
        f->lchild = p->lchild;
        delete p;
        return;
    }
    if (p->lchild == NULL)   //p只有右子树
    {
        f->lchild = p->rchild;
        delete p;
        return;
    }
    BiNode *par = p, *s = p->rchild; //p的左右子树均不空
    while (s->lchild != NULL) //查找最左下结点
    {
        par = s;
        s = s->lchild;
    }
    p->data = s->data;
    if (par == p)
        par->rchild = s->rchild; //特殊情况,p的右孩子无左子树
    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; //释放根结点
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值