04-树5 Root of AVL Tree (25分)

// AVL树的建立

#include <stdio.h>
#include <stdlib.h>

typedef struct AVLNode* AVLTree;
typedef int ElementType;
struct AVLNode {
    ElementType Data;
    AVLTree Left;
    AVLTree Right;
    int Height;
};

int Max(int a, int b) {
    return a > b ? a : b;
}

int GetHeight(AVLTree T) {
    if(!T) return -1;
    else return T->Height;
}
//这里使用getheight为了防止height为初始化的情况

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(A->Height, GetHeight(B->Right)) + 1;
    return 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 DoubleLeftRightRotation(AVLTree A) {
    A->Left = SingleRightRotation(A->Left);
    //将B与C做右单旋,返回C;
    return SingleLeftRotation(A);
    //将A与C做左单旋,返回C;
}

AVLTree DoubleRightLeftRotation(AVLTree A) {
    A->Right = SingleLeftRotation(A->Right);
    return SingleRightRotation(A);
}

AVLTree Insert(AVLTree T, int x) {
    if(!T) {
        T = (AVLTree)malloc(sizeof(struct AVLNode));
        T->Data = x;
        T->Height = 0;
        T->Left = T->Right = NULL;
    }
    else if(x > T->Data) {
        T->Right = Insert(T->Right, x);
        if(GetHeight(T->Right) - GetHeight(T->Left) == 2) {
            if(x > T->Right->Data) T = SingleRightRotation(T);
            else T = DoubleRightLeftRotation(T);
        }
    }
    else if(x < T->Data) {
        T->Left = Insert(T->Left, x);
        if(GetHeight(T->Left) - GetHeight(T->Right) == 2) {
            if(x < T->Left->Data) T = SingleLeftRotation(T);
            else T = DoubleLeftRightRotation(T);
        }
    }
    T->Height = Max(GetHeight(T->Left), GetHeight(T->Right)) + 1;
    return T;
}

int main() {
    AVLTree T = NULL;
    //方便直接insert;
    int n, x;
    scanf("%d", &n);
    while(n--) {
        scanf("%d", &x);
        T = Insert(T, x);
    }
    if(T) printf("%d\n", T->Data);
    return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值