您的位置:首页 > 其它

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

2016-10-31 12:07 393 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: