二叉搜索树(BST),也叫二叉排序树、二叉查找树:
1. 非空左子树的所有键值小于其根结点的键值。
2. 非空右子树的所有键值大于其根结点的键值。
3. 左右子树都是二叉搜索树。
// 查找X,返回该结点
// 递归
TreeNode *Find(ElementType X, TreeNode *BST)
{
if(!BST)
return NULL;
if(X>BST->Data)
return Find(X,BST->Right);
else if(X<BST->Data)
return Find(X,BST->Left);
else
return BST;
}
// 非递归
TreeNode *IterFind(ElementType X, TreeNode *BST)
{
while(BST)
{
if(X > BST->Data)
BST = BST->Right;
else if(X < BST->Data)
BST = BST->Left;
else
return BST;
}
return NULL;
}
// 查找最小值,返回该结点
// 递归
TreeNode *FindMin(TreeNode *BST)
{
if(!BST)
return NULL;
else if(!BST->Left)
return BST;
else
return FindMin(BST->Left);
}
// 非递归
TreeNode *FindMin(TreeNode *BST)
{
if(BST)
while(BST->Left)
BST = BST->Left;
return BST;
}
//查找最大值,返回该结点
//递归
TreeNode *FindMax(TreeNode *BST)
{
if(!BST)
return NULL;
else if(!BST->Right)
return BST;
else
return FindMax(BST->Right);
}
TreeNode *FindMax(TreeNode *BST)
{
if(BST)
while(BST->Right)
BST = BST->Right;
return BST;
}
TreeNode *Insert(ElementType X, TreeNode *BST) //插入X,返回该结点
{
if(!BST)
{
BST = malloc(sizeof(TreeNode));
BST->Data = X;
BST->Left = BST->Right = NULL;
}
else if(X < BST->Data)
BST->Left = Insert(X, BST->Left);
else if(X > BST->Data)
BST->Right = Insert(X, BST->Right);
return BST;
}
//删除X,返回Root。
//当删除的节点有左右子树时,可以选择左子树最大点或右子树最小点代替它,下面采用右子树最小点代替
TreeNode *Delete(ElementType X, TreeNode *BST)
{
TreeNode *Tmp;
if(!BST)
printf("要删除的元素未找到");
else if(X < BST->Data)
BST->Left = Delete( X, BST->Left);
else if(X > BST->Data)
BST->Right = Delete( X, BST->Right);
else
{
if(BST->Left && BST->Right)
{
// 右子树最小点代替
Tmp = FindMin(BST->Right);
BST->Data = Tmp->Data;
BST->Right = Delete( BST->Data,BST->Right);
}
else
{
Tmp = BST;
if(!BST->Left)
BST = BST->Right;
else if(!BST->Right)
BST = BST->Left;
}
free(Tmp);
}
return BST;
}