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

Root of AVL Tree (25)

时间:2015-06-07 23:16:52      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

果然我还是太弱了。。。这道题花了我大约5个钟头,看了各种资料,来实现一颗自平衡的搜索树

推荐大家看这个,如何一步一步写平衡二叉树

http://www.cppblog.com/cxiaojia/archive/2013/07/22/187776.html

 

平衡二叉树的难点在于插入以后,如何调整,如何计算树的高度等等等等

而递归用来解决这种问题是很简单的(一点也不简单)

#include <iostream>
using namespace std;
typedef struct treeNode{
    int data;
    struct treeNode* leftSon;
    struct treeNode* rightSon;
    int height;
}treeNode;

int max(int a, int b)
{
    if (a > b){
        return a;
    }
    else{
        return b;
    }
}
int GetHeight(treeNode *root)
{
    if (root == NULL){
        return 0;
    }
    else return root->height;
}
treeNode* RotatingL(treeNode *root)
{
    treeNode* K2 = root;
    treeNode* K1 = root->leftSon;
    K2->leftSon = K1->rightSon;
    K1->rightSon = K2;
    K2->height = max(GetHeight(K2->leftSon), GetHeight(K2->rightSon)) + 1;
    K1->height = max(GetHeight(K1->leftSon), GetHeight(K1->rightSon)) + 1;
    return K1;
}
treeNode* RotatingR(treeNode *root)
{
    treeNode* K2 = root;
    treeNode* K1 = root->rightSon;
    K2->rightSon = K1->leftSon;
    K1->leftSon = K2;
    K2->height = max(GetHeight(K2->leftSon), GetHeight(K2->rightSon)) + 1;
    K1->height = max(GetHeight(K1->leftSon), GetHeight(K1->rightSon)) + 1;
    return K1;
}
treeNode* RotatingLR(treeNode *root)
{
    root->leftSon = RotatingR(root->leftSon);
    return RotatingL(root);
}
treeNode* RotatingRL(treeNode *root)
{
    root->rightSon = RotatingL(root->rightSon);
    return RotatingR(root);
}
treeNode* insert(treeNode* root, int value)
{
    if (root == NULL){
        root = (treeNode *)malloc(sizeof(treeNode));
        root->data = value;
        root->leftSon = root->rightSon = NULL;
    }
    else if (value < root->data){
        root->leftSon = insert(root->leftSon, value);
        if (GetHeight(root->leftSon) - GetHeight(root->rightSon) == 2){
            if (value < root->leftSon->data){
                root = RotatingL(root);
            }
            else{
                root = RotatingLR(root);
            }
        }
    }
    else {
        root->rightSon = insert(root->rightSon, value);
        if (GetHeight(root->rightSon) - GetHeight(root->leftSon) == 2){
            if (value > root->rightSon->data){
                root = RotatingR(root);
            }
            else{
                root = RotatingRL(root);
            }
        }
    }

    root->height = max(GetHeight(root->leftSon), GetHeight(root->rightSon)) + 1;
    return root;
}

int main()
{
    int n;
    cin >> n;
    treeNode* root = NULL;
    for (int i = 0; i < n; i++){
        int t;
        cin >> t;
        root = insert(root, t);
    }

    cout << root->data;
}

 

Root of AVL Tree (25)

标签:

原文地址:http://www.cnblogs.com/zhouyiji/p/4559159.html

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