20120920-AVL树定义《数据结构与算法分析》

本文详细介绍了AVL树的节点声明及实现方法,包括计算节点高度、插入操作、单旋转和双旋转过程。提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

20120920-AVL树定义《数据结构与算法分析》

AVL树节点声明:

1 struct AvlNode
2 {
3     Comparable element;
4     AvlNode *left;
5     AvlNode  *right;
6     int height;
7 
8     AvlNode( const Comparable & theElement,AvlNode *lt,AvlNode *rt,int h=0):element ( theElement),left(lt),right(rt),height(t)
9 };

计算节点高度:

1 int height( AvlNode * t) const
2 {
3     return t == NULL ? -1 : t->height;
4 }

向AVL中插入操作:

void insert( const Comparable & x,AvlNode * & t)
{
    if(t == NULL)
        t = new AvlNode ( x,NULL,NULL);
    else if (x < t->element);
    {
        insert( x ,t->left);
        if(height(t->left)-height(t->right) == 2)
            if(x < t->element)
                rotateWithLeftChild(t);
            else
                doubleWithLeftChild(t);
    }
    else if (t->element < x)
    {
        insert(x,t->right);
        if(height(t->right) - height(t->left) == 2)
            if(t->right->element < x)
                rotateWithLeftChild(t);
            else
                doubleWithLeftChild(t);
    }
    else
        ;
    t->height = max(height(t->left),height(t->right))+1;
}

执行单旋转过程:

1 void rotateWithLeftChild(AvlNode * & k2)
2 {
3     AvlNode *k1 = k2->left;
4     k2->left = k1->right;
5     k1->right = k2;
6     k2->height = max(height(k2->left),height(k2->right))+1;
7     k1->height = max(height(k1->left),height(k1->right))+1;
8     k2=k1;
9 }

执行双旋转过程:

void doubleWithLeftChild( AvlNode * & k3)
{
    rotateWithLeftChild(k3->left);
    rotateWithLeftChild(k3);
}
posted @ 2012-09-20 18:37 xingoo 阅读( ...) 评论( ...) 编辑 收藏
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值