虽然是模版题但是记不住,放个3🌟回头复习。
#include <bits/stdc++.h>
using namespace std;
struct node {
int val;
node *lc, *rc;
};
node *rotateLeft (node *root) {
node *t = root->rc;
root->rc = t->lc;
t->lc = root;
return t;
}
node *rotateRight (node *root) {
node *t = root->lc;
root->lc = t->rc;
t->rc = root;
return t;
}
node *rotateRL (node *root) {
root->rc = rotateRight(root->rc);
return rotateLeft(root);
}
node *rotateLR (node *root) {
root->lc = rotateLeft (root->lc);
return rotateRight (root);
}
int getHeight (node *root) {
if (root == NULL) return 0;
return max(getHeight(root->lc), getHeight(root->rc)) + 1;
}
node *insert (node *root, int val) {
if (root == NULL) {
root = new node();
root->val = val;
root->lc = root->rc = NULL;
}
else if (val >= root->val) {
root->rc = insert(root->rc, val);
if (getHeight(root->rc) - getHeight(root->lc) == 2) {
root = val > root->rc->val ? rotateLeft (root) : rotateRL (root);
}
}
else {
root->lc = insert(root->lc, val);
if (getHeight (root->lc) - getHeight(root->rc) == 2) {
root = val < root->lc->val ? rotateRight (root) : rotateLR (root);
}
}
return root;
}
int main() {
int n, a;
node *root = NULL;
scanf ("%d", &n);
for (int i = 0; i < n; i++) {
scanf ("%d", &a);
root = insert(root, a);
}
cout << root->val;
}