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 @   xingoo  阅读(322)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示