码迷,mamicode.com
首页 > 其他好文 > 详细

AVL 树

时间:2017-07-30 13:57:33      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:bsp   style   erro   ota   malloc   ati   turn   element   stat   

SearchTree Insert(ElementType X, SearchTree T) {
    if (T == NULL) {
        T == malloc(sizeof(struct TreeNode));
        if (T == NULL) {
            Error("out of space");
        }
        else {
            T->Element = X;
            T->Left = T-Right = NULL;
        }
    }
    else if (X < T->Element) {
        T->Left = Insert(X, T->Left);
        if (Height(T->Left)-Height(T->Right) == 2)
            if (X < T->Left->Element)
                T = SingleRotateWithLeft(T);
            else 
                T = DoubleRotateWithLeft(T);
    }
    else {
        T-Right = Insert(X, T->Right);
        if (Height(T->Right)-Height(T->Left) == 2)
            if (X > T->Right->Element)
                T = SingleRotateWithLeft(T);
            else 
                T = DoubleRotateWithLeft(T);
    }     
    T->Height = Max(Height(T->Left, Height(T->Right))) + 1;
    return T;
}

static Position SingleRotateWithLeft(Position K2) {
    Position K1;

    K1 = K2->Left;
    K2->Left = K1->Right;
    K1->Right = K2;
    K2->Height = Max(Height(K2->Left), Height(K2->Right)) + 1;
    K1->Height = Max(Height(K1->Left), K2->Height) + 1;

    reutrn K1;
}

static Position DoubleRotateWithLeft(Position K3) {
    K3->Left = SingleRotateWithLeft(K3->Left);
    return SingleRotateWithLeft(K3);
}

 

AVL 树

标签:bsp   style   erro   ota   malloc   ati   turn   element   stat   

原文地址:http://www.cnblogs.com/m2492565210/p/7258757.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!