Binary Search Tree
一颗二叉树,可以为空;如果不为空,则满足下列性质:
>非空左子树的所有键值小于其根结点的键值
>非空右子树的所有键值大于其根结点的键值
>左、右子树都是BST
BST操作的特殊函数
Position Find(ElementType x, BinTree BST):从BST中查找元素X,返回其所在结点的地址
Position Find(int x, BinTree BST)
{
while(BST){
if (x>BST->val)
BST = BST->right;//向右查找
else if(x<BST->val)
BST = BST->left;//向左查找
else
return BST;//查找成功
}
return NULL;//返回空树,查找失败
}
Position FindMin(BinTree BST):从BST中查找并返回最小元素所在的结点地址
Position FindMin(BinTree BST)
{
while(BST){
BST = BST->left;//BST中最小值一定是最左边的结点
}
return NULL;
}
Position FindMax(BinTree BST):从BST中查找并返回最大元素所在结点地址
Position FindMax(BinTree BST)
{
while(BST){
BST = BST->right;//BST中最大的值一定是最右边结点
}
return NULL;
}
BinTree Insert(Element x, BinTree BST):插入BST
BinTree Insert(int x, BinTree BST)
{
if (!BST){//该BST是空,在这里插入
BST = (BinTree)malloc(sizeof(struct BinSearchTree));
BST->val = x;
BST->left = BST->right = NULL;
}else{
if (x>BST->val)
BST->right = Insert(x, BST->right);//比BST大,则插入BST的右子树,记录指针
else if(x<BST->val)
BST->left = Insert(x, BST->left);//比BST小,则插入BST的左子树,记录指针
}
return BST;
}
BinTree Delete(Element x, BinTree BST):删除BST中的结点
删除结点比较复杂,考虑三种情况
>删除叶子leaf结点:直接删除,将父结点指针置NULL
>删除结点只有一个左、右子树:将父节点的指针指向要删除结点的孩子结点
>删除结点有左、右子树:用另一节点替代被删除结点:右子树的最小元素或者左子树的最大元素
BinTree Delete(int x, BinTree BST)
{
BinTree tmp;
if (!BST)
printf("未找到删除结点");
else if (x<BST->val){
BST->left = Delete(x, BST->left);
}
else if(x>BST->val){
BST->right = Delete(x, BST->right);
}
else{
if (BST->left && BST->right){
tmp = FindMin(BST->right);
BST->val = tmp->val;
BST->right = Delete(BST->val, BST->right);
}else{
tmp = BST;
if (!BST->left)
BST = BST->right;
else if(!BST->right)
BST = BST->left;
free(tmp);
}
}
return BST;
}
最后,贴上完整代码
#include <stdio.h>
#include <string.h>
#include <malloc.h>
struct BinSearchTree
{
int val;
struct BinSearchTree *left;
struct BinSearchTree *right;
};
typedef struct BinSearchTree *BinTree;
typedef struct BinSearchTree *Position;
Position Find(int x, BinTree BST)
{
while(BST){
if (x>BST->val)
BST = BST->right;
else if(x<BST->val)
BST = BST->left;
else
return BST;
}
return NULL;
}
Position FindMin(BinTree BST)
{
while(BST){
BST = BST->left;
}
return NULL;
}
Position FindMax(BinTree BST)
{
while(BST){
BST = BST->right;
}
return NULL;
}
BinTree Insert(int x, BinTree BST)
{
if (!BST){
BST = (BinTree)malloc(sizeof(struct BinSearchTree));
BST->val = x;
BST->left = BST->right = NULL;
}else{
if (x>BST->val)
BST->right = Insert(x, BST->right);
else if(x<BST->val)
BST->left = Insert(x, BST->left);
}
return BST;
}
BinTree Delete(int x, BinTree BST)
{
BinTree tmp;
if (!BST)
printf("未找到删除结点");
else if (x<BST->val){
BST->left = Delete(x, BST->left);
}
else if(x>BST->val){
BST->right = Delete(x, BST->right);
}
else{
if (BST->left && BST->right){
tmp = FindMin(BST->right);
BST->val = tmp->val;
BST->right = Delete(BST->val, BST->right);
}else{
tmp = BST;
if (!BST->left)
BST = BST->right;
else if(!BST->right)
BST = BST->left;
free(tmp);
}
}
return BST;
}
int main(int argc, char *argv[])
{
return 0;
}