* 左左就右旋,右右就左旋

 

#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;
}

 

 

 
分类: 未分类

0 条评论

发表回复

Avatar placeholder

您的邮箱地址不会被公开。 必填项已用 * 标注