《数据结构与算法分析》--二叉查找树

二叉查找树的结构:

struct TreeNode
{
    ElementType element;
    TreeNode* left;
    TreeNode* right;
};
typedef TreeNode* SearchTree;
typedef TreeNode* position;

二叉查找树的操作声明:

//清空树
SearchTree MakeEmpty(SearchTree t)
{
    if(t!=NULL)
    {
        MakeEmpty(t->left);
        MakeEmpty(t->right);
        free(t);
    }
    return NULL;    
}
//插入操作
position Insert(ElementType x,SearchTree t)
{
    if(t==NULL)
    {
        t=new TreeNode;
        t->element=x;
        t->left=t->right=NULL;
    }
    else
    {
        if(x < t->element)
        {
            t->left=Insert(x,t->left);//左子树指向左儿子
        }
        if(x > t->element)
        {
            t->right=Insert(x,t->right);//右子树指向右儿子
        }
    }
    return t;//返回的是根节点的地址
}
//删除操作
position Delete(ElementType x,SearchTree t)
{
    position tmp;
    if(t==NULL)
        return NULL;
    else if(x < t->element)
    {
        t->left=Delete(x,t->left);
    }
    else if(x > t->element)
    {
        t->right=Delete(x,t->right);
    }
    else if(t->left && t->right)
    {
        temp=FindMin(t->left);
        t->element=temp->element;
        t->right=Delete(t->element,t->right);
    }
    else 
    {
        temp=t;
        if(t->left==NULL)
            t=t->right;
        if(t->right==NULL)
            t=t->left;
        free(temp);
    }
    return t;
}
//查找操作
position Find(ElementType x,SearchTree t)
{
    if(t==NULL)
        return NULL;
    else if(x < t->element)
    {
        return Find(x,t->left);
    }
    else if(x > t->element)
    {
        return Find(x,t->right);
    }
    else 
        return t;
}
//查找最大值操作
position FindMax(SearchTree t)
{
    if(t==NULL)
        return NULL;
    else if(t->right!=NULL)
        return FindMax(t->right);
    else
        return t;
}
//查找最小值操作
position FindMin(SearchTree t)
{
    if(t==NULL)
        return NULL;
    else if(t->left!=NULL)
        return FindMin(t->left);
    else
        return t;
}

       二叉查找树相对来说比较简单,操作较少。在上述操作中,最难的是Delete操作,Delete操作一定要分为四种情况。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值