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 @ 2017-05-19 22:06  罗志均  阅读(143)  评论(0编辑  收藏  举报
友情链接:回力 | 中老年女装 | 武汉英语培训机构 | 留学费用一览表 | 托福考试费用