1066. Root of AVL Tree (25)解题报告

来源:互联网 发布:词根词缀字典 知乎 编辑:程序博客网 时间:2024/05/18 00:49
#define _CRT_SECURE_NO_WARNINGS#include <cstdio>#include <cstdlib>struct node {    int data, height;    node *left, *right;};node *LL(node *A);node *RR(node *A);node *LR(node *A);node *RL(node *A);node *insert(node *root, int data);int getheight(node *A);int max(int a, int b);int main(void) {    int n, i, tmp;    node *root = nullptr;    scanf("%d", &n);    for (i = 0; i < n; i++) {        scanf("%d", &tmp);        root = insert(root, tmp);    }    printf("%d\n", root->data);    return 0;}node *LL(node *A) {    node *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), getheight(B->right)) + 1;    return B;}node *RR(node *A) {    node *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->left), getheight(B->right)) + 1;    return B;}node *LR(node *A) {    A->left = RR(A->left);    return LL(A);}node *RL(node *A) {    A->right = LL(A->right);    return RR(A);}node *insert(node *root, int data) {    if (!root) {        root = new node;        root->data = data;        root->left = root->right = nullptr;    }    else if(root->data > data) {        root->left = insert(root->left, data);        if (getheight(root->left) - getheight(root->right) == 2) {            if (root->left->data > data) {                root = LL(root);            }            else {                root = LR(root);            }        }    }    else {        root->right = insert(root->right, data);        if (getheight(root->right) - getheight(root->left) == 2) {            if (root->right->data > data) {                root = RL(root);            }            else {                root = RR(root);            }        }    }    root->height = max(getheight(root->left), getheight(root->right)) + 1;    return root;}int getheight(node *A) {    if (!A) {        return 0;    }    else {        return A->height;    }}int max(int a, int b) {    return a >= b ? a : b;}
0 0