码迷,mamicode.com
首页 > 其他好文 > 详细

平衡二叉树平衡调整代码

时间:2018-10-26 14:22:58      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:ace   print   ==   平衡   get   getheight   max   scan   获取   

#include <iostream>
using namespace std;
struct node {
    int val;
    struct node *left, *right;
};
node *rotateLeft(node *root) {//左旋 可以记下来 余下都可反推
    node *t = root->right;
    root->right = t->left;
    t->left = root;
    return t;
}
node *rotateRight(node *root) {//右旋
    node *t = root->left;
    root->left = t->right;
    t->right = root;
    return t;
}
node *rotateLeftRight(node *root) {//先左子树左旋在整体右旋
    root->left = rotateLeft(root->left);
    return rotateRight(root);
}
node *rotateRightLeft(node *root) {//先右子树右旋在整体左旋
    root->right = rotateRight(root->right);
    return rotateLeft(root);
}
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;
}

 

平衡二叉树平衡调整代码

标签:ace   print   ==   平衡   get   getheight   max   scan   获取   

原文地址:https://www.cnblogs.com/haleypei/p/9855832.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!