二叉搜索树是一种特殊的二叉树,它的特点是所有左子树的关键字都比根节点小,所有右子树的关键字都比根节点大,且左右子树均是二叉搜索树。因此,在这种树结构中查找某一关键字就变得很方便。下面是二叉搜索树相关的函数实现方法。
1、二叉搜索树数据类型定义
<span style="font-size:18px;">typedef struct TreeNode{
ElemType data;
struct TreeNode *Left;
struct TreeNode *Right;
}BinTree;</span>
2、对二叉搜索树的基本操作
<span style="font-size:18px;">BinTree* creatBinTree();//创建一棵树
BinTree* Find(ElemType X,BinTree *BST);//查找树中关键字X
BinTree* FindMin(BinTree *BST);//查找树中最小的元素
BinTree* FindMax(BinTree *BST);//查找树中最大的元素
BinTree* Insert(ElemType X,BinTree *BST);//向二叉搜索树中插入元素
BinTree* Delete(ElemType X,BinTree *BST);//删除二叉树中的某一元素</span>
3、代码实现
<span style="font-size:18px;">BinTree* creatBinTree()
{
BinTree *BT;
BT=(BinTree*)malloc(sizeof(BinTree));
BT->Left=NULL;
BT->Right=NULL;
return BT;
}
BinTree* Find(ElemType X,BinTree *BST)
{
BinTree *T=BST;
while(T)
{
if(T->data>X)
{
T=T->Left;
}
else if(T->data<X)
{
T=T->Right;
}
else
{
return T;
}
}
return NULL;
}
/*
BinTree* FindMin(BinTree *BST)
{
BinTree *T=BST;
if(!T) return NULL;
else if(T->Left)
return FindMin(T->Left);
else
return T;
}
*/
BinTree* FindMin(BinTree *BST)
{
BinTree *T=BST;
while(T)
{
if(T->Left==NULL)return T;
T=T->Left;
}
}
BinTree* FindMax(BinTree *BST)
{
BinTree *T=BST;
while(T)
{
if(T->Right==NULL)return T;
T=T->Right;
}
}
/*
BinTree* FindMax(BinTree *BST)
{
BBinTree *T=BST;
if(!T) return NULL;
else if(T->Right)
return FindMin(T->Right);
else
return T;
}
*/
BinTree* Insert(ElemType X,BinTree *BST)
{
BinTree *T=BST;
if(!T)
{
BinTree *BT=(BinTree*)malloc(sizeof(BinTree));
BT->data=X;
BT->Left=NULL;
BT->Right=NULL;
BST=BT;
return BST;
}
while(T)
{
if(T->data>X)
{
if(!T->Left)
{
BinTree *BT=(BinTree*)malloc(sizeof(BinTree));
BT->data=X;
BT->Left=NULL;
BT->Right=NULL;
T->Left=BT;
return BST;
}
T=T->Left;
}
else if(T->data<X)
{
if(!T->Right)
{
BinTree *BT=(BinTree*)malloc(sizeof(BinTree));
BT->data=X;
BT->Left=NULL;
BT->Right=NULL;
T->Right=BT;
return BST;
}
T=T->Right;
}
}
return BST;
}
BinTree* Delete(ElemType X,BinTree *BST)
{
if(!BST)printf("ûÓÐÕÒµ½¸ÃÔªËØ\n");
else if(BST->data>X)
BST->Left=Delete(X,BST->Left);
else if(BST->data<X)
BST->Right=Delete(X,BST->Right);
else
{
if(BST->Left && BST->Right)
{
BinTree *tmp=FindMin(BST->Right);
BST->data=tmp->data;
BST->Right=Delete(BST->data,BST->Right);
}
else
{
BinTree *tmp=BST;
if(!BST->Left)
{
BST=BST->Right;
}
else if(!BST->Right)
{
BST=BST->Left;
}
free(tmp);
}
}
return BST;
}
int main()
{
BinTree *BT=Insert(12,NULL);
BT=Insert(9,BT);
BT=Insert(11,BT);
BT=Insert(4,BT);
BT=Insert(8,BT);
BT=Insert(13,BT);
BT=Insert(14,BT);
printf("before delete\n");
BinTree *re=Find(12,BT);
if(re)
printf("%d \n",re->data);
else
printf("no found!!\n");
BT=Delete(12,BT);
printf("after delete\n");
re=Find(12,BT);
if(re)
printf("%d \n",re->data);
else
printf("no found!!\n");
return 0;
}</span>