//二叉搜索树查找操作Find
Position Find(ElementType X, BinTree 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;
}
//循环实现
Position IterFind(ElementType X, BinTree BST)
{
while (BST)
{
if (X > BST->Data)
BST = BST->Right;
else if (X < BST->Data)
BST = BST->Left;
else
return BST;
}
return NULL;
}
//查找最小元素递归函数
Position FindMin(BinTree BST)
{
if (!BST) return NULL;
else if (!BST->Left)
return BST;
else
return FindMin(BST->Left);
}
//查找最大元素的迭代函数
Position FindMax(BinTree BST)
{
if (BST)
while (BST->Right)
BST = BST->Right;
return BST;
}
//二叉搜索树的插入
BinTree Insert(ElementType X, BinTree BST)
{
if (!BST)
{
BST = malloc(sizeof(struct 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(XX, BST->Right);
return BST;
}
//二叉树的删除
BinTree Delete(ElementType X, BinTree BST)
{
Position 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;
}
二叉搜索树的查找,插入和删除
最新推荐文章于 2024-09-02 15:59:20 发布