数据结构| |二叉搜索树基本操作(递归)

接口实现
//对二叉搜索树插入一个数据
int BSTreeInsertR(BSTreeNode** root, BSTDataType x)
//查找一个数据
BSTreeNode* BSTreeFindR(BStreeNode** root, BSTDataType x)
//删除一个数据
int BStreeRemoveR(BStreeNode** root, BSTDataType x)

//Buy结点
BSTreeNode* BuyBSTreeNode(BSTDataType x)
{
    BSTreeNode* newNode = (BSTreeNode*)malloc(sizeof(BSTreeNode));
    if (newNode == NULL)
    {
        perror("malloc for memory!");
    }

    newNode->_data = x;
    newNode->_left = NULL;
    newNode->_right = NULL;

    return newNode;
}

//插入一个数据
int BSTreeInsertR(BSTreeNode** root, BSTDataType x)
{
    assert(root);

    if (*root == NULL)
    {
        *root = BuyBSTreeNode(x);
        return 1;
    }

    if ((*root)->_data > x)
    {
        return BSTreeInsertR(&(*root)->_left, x);
    }
    else if ((*root)->_data < x)
    {
        return BSTreeInsertR(&(*root)->_right, x);
    }
    else
    {
        return 0;
    }
}

//查找一个数据
BSTreeNode* BSTreeFindR(BSTreeNode** root, BSTDataType x)
{
    assert(root);

    if (*root == NULL)
    {
        return NULL;
    }

    if ((*root)->_data > x)
    {
        return BSTreeFindR(&(*root)->_left, x);
    }
    else if ((*root)->_data < x)
    {
        return BSTreeFindR(&(*root)->_right, x);
    }
    else
    {
        return *root;
    }
}

//删除一个数据
int BSTreeRemoveR(BSTreeNode** root, BSTDataType x)
{
    assert(root);

    if (*root == NULL)
    {
        return 0;
    }

    if ((*root)->_data > x)
    {
        return BSTreeRemoveR(&(*root)->_left, x);
    }
    else if ((*root)->_data < x)
    {
        return BSTreeRemoveR(&(*root)->_right, x);
    }
    else
    {
        BSTreeNode* del = *root;
        //找到,删除
        //左结点为空或者右结点为空
        if ((*root)->_left == NULL)
        {
            *root = (*root)->_right;
            free(del);
            del = NULL;
        }
        else if ((*root)->_right == NULL)
        {
            *root = (*root)->_left;
            free(del);
            del = NULL;
        }
        else
        {
            BSTreeNode* replace = (*root)->_right;
            while (replace->_left)
            {
                replace = replace->_left;
            }

            (*root)->_data = replace->_data;
            return BSTreeRemoveR(&(*root)->_right, replace->_data);
        }
    }
    return 1;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值