详解平衡二叉树(AVL tree)平衡操作(图+代码)
* 左左就右旋,右右就左旋
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 1e9; const int maxm = 1e5 + 5; const int inf = 2147483647; using namespace std; struct node { node *left, *right; int key; }; node *LL(node *root) { node *t = root->left; root->left = t->right; t->right = root; return t; } node *RR(node *root) { node *t = root->right; root->right = t->left; t->left = root; return t; } node *RL(node *root) { root->right = LL(root->right); return RR(root); } node *LR(node *root) { root->left = RR(root->left); return LL(root); } int getHight(node *root) { if (root == NULL)return 0; return max(getHight(root->left), getHight(root->right)) + 1; } node *insert(node *root, int val) { if (root == NULL) { root = new node(); root->key = val; root->left = root->right = NULL; } else if (val < root->key) { root->left = insert(root->left, val); if (getHight(root->left) - getHight(root->right) == 2) root = val < root->left->key ? RR(root) : LR(root); } else { root->right = insert(root->right, val); if (getHight(root->right) - getHight(root->left) == 2) root = val > root->right->key ? LL(root) : RL(root); } return root; } int main() { int n, k; cin >> n; node *root = NULL; for (int i = 1; i <= n; i++) { cin >> k; root = insert(root, k); } return 0; }