AVL树的旋转、插入、删除及遍历C语言实现

MARK一篇关于AVL树的博客文章:数据结构图文解析之:AVL树详解及C++模板实现

一、AVL结构定义


struct AVLNode
{
    struct AVLNode *lchild,*rchild;
    int key;
    int height;//保存树的高度
};

二、几个函数

int Max(int a,int b)
{
    return a>b?a:b;
}
int ComputeHeight(struct AVLNode *T)
{
    if(T)
        return T->height;
    return 0;
}

三、AVL的旋转

struct AVLNode *leftRotation(struct AVLNode *root)//左旋操作,对应于RR
{
    struct AVLNode *p=root->rchild;
    root->rchild=p->lchild;
    p->lchild=root;
    root->height=Max(ComputeHeight(root->lchild),ComputeHeight(root->rchild))+1;
    p->height=Max(ComputeHeight(p->lchild),ComputeHeight(p->rchild))+1;
    return p;
}
struct AVLNode *rightRotation(struct AVLNode *root)//右旋操作,对应于LL
{
    struct AVLNode *p=root->lchild;
    root->lchild=p->rchild;
    p->rchild=root;
    root->height=Max(ComputeHeight(root->lchild),ComputeHeight(root->rchild))+1;
    p->height=Max(ComputeHeight(p->lchild),ComputeHeight(p->rchild))+1;
    return p;
}
struct AVLNode *rightleftRotation(struct AVLNode *root)//先右旋,再左旋操作,对应于RL
{
    root->rchild=rightRotation(root->rchild);//失衡节点右儿子进行一次右旋操作
    return leftRotation(root);//失衡节点进行一次左旋
}
struct AVLNode *leftrightRotation(struct AVLNode *root)//先左旋,再右旋操作,对应于LR
{
    root->lchild=leftRotation(root->lchild);//失衡节点左儿子进行一次左旋操作
    return rightRotation(root);//失衡节点进行一次右旋
}

四、AVL的插入

void InsertNode(int e,struct AVLNode **T)
{
    if((*T)==NULL)
    {
        (*T)=(struct AVLNode*)malloc(sizeof(struct AVLNode));
        (*T)->lchild=(*T)->rchild=NULL;
        (*T)->key=e;
        (*T)->height=0;
    }
    else if(e<((*T)->key))
    {
        InsertNode(e,&(*T)->lchild);//插入左子树
        if(ComputeHeight((*T)->lchild)-ComputeHeight((*T)->rchild)==2)//失衡
        {
            e<(*T)->lchild->key?((*T)=rightRotation(*T)):((*T)=leftrightRotation(*T));
        }
    }
    else if(e>(*T)->key)
    {
        InsertNode(e,&(*T)->rchild);//插入右子树
        if(ComputeHeight((*T)->rchild)-ComputeHeight((*T)->lchild)==2)
        {
            e>(*T)->rchild->key?((*T)=leftRotation(*T)):((*T)=rightleftRotation(*T));
        }
    }
    (*T)->height=Max(ComputeHeight((*T)->lchild),ComputeHeight((*T)->rchild))+1;//更新节点高度
}

转载于:https://www.cnblogs.com/xLester/p/7570384.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值