平衡二叉树的调整模版

2015-11-21 00:58:28 · 作者: · 浏览: 5
typedef struct avltreenode *avltree;
typedef struct avltreenode{
    int data;
    avltree left;
    avltree right;
    int height;
};

int getheight(avltree a)
{
    if(a==NULL) return -1;
    return a->height;
}

//a必须有一个左子结点b
//a与b做左单旋,更新a与b高度,返回新的根结点b
avltree singleleftrotation(avltree a)
{
    avltree b=a->left;
    a->left=b->right;
    b->right=a;
    a->height=max(getheight(a->left),getheight(a->right))+1;
    b->height=max(getheight(b->left),a->height)+1;

    return b;
}

//右单旋
avltree singlerightrotation(avltree a)
{
    avltree b=a->right;
    a->right=b->left;
    b->left=a;

    a->height=max(getheight(a->left),getheight(a->right))+1;
    b->height=max(getheight(b->right),a->height)+1;

    return b;
}

//左右双旋
//a必须有一个左子结点b,且b必须有一个右子结点c
//a,b,c,做两次单旋,返回新的根结点c
//先对b和c做右单旋,在对a和c做左单旋
avltree doubleleftrightrotation(avltree a)
{
    a->left=singlerightrotation(a->left);

    return singleleftrotation(a);
}

//右左双旋
avltree doublerightleftrotation(avltree a)
{
    a->
right=singleleftrotation(a->right); return singlerightrotation(a); } avltree avl_insertion(int x,avltree t) { /*将X插入avl树T中,并返回调整后的avl树*/ if(!t)/*插入空树,则新建包含一个结点的树*/ { t=(avltree)malloc(sizeof(struct avltreenode)); t->data=x; t->height=0; t->left=t->right=NULL; }/*插入空树结束*/ else if(x data) { t->left=avl_insertion(x,t->left); if(getheight(t->left)-getheight(t->right)==2) { /*需要左旋*/ if(x left->data) t=singleleftrotation(t);//左单旋 singleleftrotation else t=doubleleftrightrotation(t);//左右双旋 } } else if(x>t->data) { t->right=avl_insertion(x,t->right); if(getheight(t->left)-getheight(t->right)==-2) { /*需要右旋*/ if(x>t->right->data) t=singlerightrotation(t);//右单旋 else t=doublerightleftrotation(t);//右左双旋 } } //x=data,无须插入 t->height=max(getheight(t->left),getheight(t->right))+1; return t; }

?