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

AVL树左旋右旋学习总结

时间:2020-06-13 19:38:50      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:nbsp   using   学习总结   its   color   std   inline   i++   for   

#include <bits/stdc++.h>
using namespace std;

//左->data<节点->data<右->data
struct node{
    int data;
    node *lft, *rht;
    node(int data):data(data), lft(0),rht(0){}
};
inline node* rotate_lft( node *root ){      //当左子树是一条直线时,对左子树旋转,如8-7-6
    node *tmp = root->lft;
    root->lft = tmp->rht;                   //!!
    tmp->rht = root;
    return tmp;
}

inline node* rotate_rht( node *root ){      //当右子树是一条直线时,对右子树旋转
    node *tmp = root->rht;
    root->rht = tmp->lft;
    tmp->lft = root;
    return tmp;
}

inline node* rotate_rht_lft( node *root ){  //左子树转弯,双旋
    root->lft = rotate_rht(root->lft);
    return rotate_lft(root);
}

inline node* rotate_lft_rht( node *root ){  //右子树转弯,双旋
    root->rht = rotate_lft(root->rht);
    return rotate_rht(root);
}

inline int Hight( node *root ){
    if( !root ) return 0;
    return max(Hight(root->lft), Hight(root->rht)) + 1;
}

inline node* Insert( node *root, int &data ){
    if( !root ) root = new node(data);
    else if( data>root->data ){
        root->rht = Insert(root->rht, data);
        if( Hight(root->rht)-Hight(root->lft)==2 )
            root = data < root->rht->data ? rotate_lft_rht(root):rotate_rht(root);
    }else{
        root->lft = Insert(root->lft, data);
        if( Hight(root->lft)-Hight(root->rht)==2 )
            root = data > root->lft->data ? rotate_rht_lft(root):rotate_lft(root);
    }

    return root;
}

int n;
int main()
{
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    cin >> n;
    node *root = 0;
    for( int i=0; i<n; i++ ){
        int data;
        cin >> data;
        root = Insert(root, data);
    }
    cout << root->data << "\n";

    return 0;
}

 

AVL树左旋右旋学习总结

标签:nbsp   using   学习总结   its   color   std   inline   i++   for   

原文地址:https://www.cnblogs.com/WAautomaton/p/13121310.html

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