AVL树

AVL树是其每一个节点的左子树和右子树的高度差最多差1的二叉查找树。

///////////Avl树//////////////
struct AvlNode;
typedef struct AvlNode* AvlTree;
typedef struct AvlNode* Position;

struct AvlNode{
    ElementType element;
    AvlTree left;
    AvlTree right;
    int height;  //存储高度信息
}

//返回高度信息
int get_height(Position P){
    if(P==NULL){
        return -1;
    }
    else{
        return P->height;
    }
}

//插入元素到AVL树的例程 重难点
AvlTree Insert(ElementType x,AvlTree T){
    if(T==NULL){
        AvlTree T=malloc(sizeof(struct AvlNode));
        T->element=x;
        T->left=NULL;
        T->right=NULL;
        T->height=0;
        //return T;
    }
    else if(x < T->element){
        T->left=Insert(x,T->left);
        //处理左平衡条件
        if((get_height(T->left)-get_height(T->right))==2 /* >1 */){
            if(x < T->left->element){  //左左
                T=SingleRorateWithLeft(T);
            }
            else{  //左右
                T=DoubleRotateWithLeft(T);
            }
        }   
    }
    else if(x > T->element){
        T->right=Insert(x,T->right);
        //同理,处理右平衡条件
        if((get_height(T->right) - get_height(T->left))==2){
            if(x > T->right->element){  //右右
                T=SingleRorateWithRight(T);
            }
            else{  //右左
                T=DoubleRotateWithRight(T);
            }
        }

    }
    else{
        //x is already exists,do nothing
    }

    //高度信息修改
    T->height=max(get_height(T->left),get_height(T->right))+1;
    return T;
}

//单旋转例程 左左
Position SingleRorateWithLeft(Position K2){
    //初始化
    Position K1;
    K1=K2->left;

    //旋转
    K2->left=K1->right;
    K1->right=K2;

    //更新高度信息
    K2->height=max(get_height(K2->left),get_height(K2->right))+1;
    K1->height=max(get_height(K1->left),get_height(K1->right)/*K2->height*/)+1;

    //返回新节点
    return K1;  
}

//右右
Position SingleRorateWithRight(Position K2){
    Position K1;
    K1=K2->right;

    K2->right=K1->left;
    K1->left=K2;

    K2->height=max(get_height(K2->left),get_height(K2->right))+1;
    K1->height=max(get_height(K1->left),get_height(K1->right))+1;

    return K1;
}

//双旋转例程 左右
Position DoubleRotateWithLeft(Position K3){

    K3->left=SingleRorateWithRight(K3->left);

    return SingleRorateWithLeft(K3);
}

//双旋转例程 右左
Position DoubleRotateWithRight(Position K3){

    K3->right=SingleRorateWithLeft(K3->right);

    return SingleRorateWithRight(K3);
}

你可能感兴趣的:(AVL树)