/*二叉搜索树的查找操作*/
//查找效率决定于树的高度
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;//空的二叉搜索树,返回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;
}
/*二叉搜索树的插入*/
position 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->right)
{
bst->right=insert(x,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->right)
{
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;
}