首页 > 编程语言 > 详细

avl tree c++

时间:2019-05-20 16:12:47      阅读:140      评论:0      收藏:0      [点我收藏+]
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include<algorithm>
using namespace std;
struct node {
    int val;
    node* left,  * right;
};
node* rotateLeft(node* root) {//left down
    node* t = root->right;//0
    root->right = t->left;//   0 ->    0
    t->left = root;//               0
    return t;
}
node* rotateRight(node* root) {//right down
    node* t = root->left;//   0    
    root->left = t->right;//0     ->   0  
    t->right = root;//                    0
    return t;
}
node* rotateLeftRight(node* root) {//        0             0      
    root->left = rotateLeft(root->left);//0        ->    0     ->    0
    return rotateRight(root);//              0        0           0     0
}
node* rotateRightLeft(node* root) {//        0 
    root->right = rotateRight(root->right);//   0
    return rotateLeft(root);//               0 
}
int getHeight(node* root) {
    if (root == NULL) return 0;
    return max(getHeight(root->left), getHeight(root->right)) + 1;
}
node* insert(node * root, int val) {
    if (root == NULL) {
        root = new node();
        root->val = val;
        root->left = root->right = NULL;
    }
    else if (val < root->val) {
        root->left = insert(root->left, val);
        if (getHeight(root->left) - getHeight(root->right) == 2)
            root = val < root->left->val ? rotateRight(root) : rotateLeftRight(root);
    }
    else {
        root->right = insert(root->right, val);
        if (getHeight(root->left) - getHeight(root->right) == -2)
            root = val > root->right->val ? rotateLeft(root) : rotateRightLeft(root);
    }
    return root;
}
int main() {
    int n, val;
    scanf("%d", &n);
    node* root = NULL;
    for (int i = 0; i < n; i++) {
        scanf("%d", &val);
        root = insert(root, val); 
    }
    printf("%d", root->val);
    return 0;
}

 

avl tree c++

原文:https://www.cnblogs.com/masayoshi/p/10894600.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!