二叉查找树详解

二叉查找树性质

1、二叉树

每个树的节点最多有两个子节点的树叫做二叉树。

2、二叉查找树

一颗二叉查找树是按照二叉树的结构来组织的,并且满足一下性质:
一个节点所有左子树上的节点不大于盖节点,所有右子树的节点不小于该节点。
对查找树的操作查询,插入,删除等操作的时间复杂度和树的高度成正比, 因此,构建高效的查找树尤为重要。

查找树的遍历

先序遍历

查找树的遍历可以很简单的采用递归的方法来实现。

struct list
{
    struct list *left;//左子树
    struct list *right;//右子树
    int a;//结点的值
};
void preorder(struct list  *t)//t为根节点的指针
{
    if(t!=NULL)
    {
        printf("%d,",t->a);
        preorder(t->left);
        perorder(t->right);
    }
}

中序遍历

struct list
{
    struct list *left;//左子树
    struct list *right;//右子树
    int a;//结点的值
};
void preorder(struct list  *t)//t为根节点的指针
{
    if(t!=NULL)
    {
        preorder(t->left);
        printf("%d,",t->a);
        perorder(t->right);
    }
}

后序遍历

struct list
{
    struct list *left;//左子树
    struct list *right;//右子树
    int a;//结点的值
};
void preorder(struct list  *t)//t为根节点的指针
{
    if(t!=NULL)
    {
        preorder(t->left);
        perorder(t->right);
        printf("%d,",t->a);
    }
}

查找树的搜索

给定关键字k,进行搜索,返回结点的指针。

struct list
{
    struct list *left;//左子树
    struct list *right;//右子树
    int a;//结点的值
};
struct list * search(struct list *t,int k)
{
    if(t==NULL||t->a==k)
        return t;
    if(t->a<k)
        search(t->right);
    else
        search(t>left);
};

也可以用非递归的形式进行查找

struct list
{
    struct list *left;//左子树
    struct list *right;//右子树
    int a;//结点的值
};
struct list * search(struct list *t,int k)
{
    while(true)
    {
        if(t==NULL||t->a==k)
        {
            return t;
            break;
        }
        if(t->a<k)
            t=t->rigth;
        else
            t=t->left;

    }
};

最大值和最小值查询

根据查找树的性质,最小值在最左边的结点,最大值的最右边的 结点,因此,可以直接找到。
下面是最大值的例子:

{
    struct list *left;//左子树
    struct list *right;//右子树
    int a;//结点的值
};
struct lsit *max_tree(struct lsit *t)
{
    while(t!=NULL)
    {
        t=t->right;
    }
    return t;
};

查找树的插入和删除

插入和删除不能破坏查找树的性质,因此只需要根据性质,在树中找到相应的位置就可以进行插入和删除操作。

struct list
{
    struct list *left;//左子树
    struct list *right;//右子树
    int a;//结点的值
};
void insert(struct list *root,struct list * k)
{
    struct list *y,*x;
    x=root;
    while(x!=NULL)
    {
        y=x;
        if(k->a<x->a)
        {
            x=x->left;
        }
        else
            x=x->right;
    }
    if(y==NULL)
        root=k;
    else if(k->a<y->a)
        y->left=k;
    else
        y->right=k;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值