1. AVL树 维基百科
2. 别人的题解
参考了这两份资料,不得不说那位同学的AVL树写得很漂亮.. 我之前试图用类来封装那些方法,写的跟屎一样。。
代码:
#include <iostream>
#include <cmath>
using namespace std;
struct Node
{
Node *left;
Node *right;
int value;
int height;
Node(int val): left(0), right(0), value(val), height(0) {}
};
int get_height(Node* node)
{
return node==0? -1: node->height;
}
bool is_balanced(Node *node)
{
return abs(get_height(node->left)-get_height(node->right)) <= 1;
}
Node* rotate_right(Node* root)
{
Node* new_root = root->left;
root->left = new_root->right;
new_root->right = root;
root->height = max(get_height(root->left), get_height(root->right)) + 1;// cannot use "root->height = get_height(root);" here
new_root->height = max(get_height(new_root->left), get_height(new_root->right)) + 1;
return new_root;
}
Node* rotate_left(Node *root)
{
Node* new_root = root->right;
root->right = new_root->left;
new_root->left = root;
root->height = max(get_height(root->left), get_height(root->right)) + 1;// cannot use "root->height = get_height(root);" here
new_root->height = max(get_height(new_root->left), get_height(new_root->right)) + 1;
return new_root;
}
Node* insert(Node* root, int val)
{
if (root == NULL)
{
return new Node(val);
}
if (val < root->value) // insert left
{
root->left = insert(root->left, val);
if (is_balanced(root) == false)
{
if (val < root->left->value) // LL
{
root = rotate_right(root);
} else // LR
{
root->left = rotate_left(root->left); // attention!
root = rotate_right(root);
}
}
} else
{
root->right = insert(root->right, val);
if (is_balanced(root) == false)
{
if (val > root->right->value) // RR
{
root = rotate_left(root);
} else // RL
{
root->right = rotate_right(root->right); // attention!
root = rotate_left(root);
}
}
}
root->height = max(get_height(root->left), get_height(root->right)) + 1;
return root;
}
int main()
{
int n, tmp;
Node* root = NULL;
cin >> n;
while ( n -- )
{
cin >> tmp;
root = insert(root, tmp);
}
cout << root->value;
return 0;
}