接口实现
//对二叉搜索树插入一个数据
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;
}