AVL树左旋右旋学习总结
Posted waautomaton
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AVL树左旋右旋学习总结相关的知识,希望对你有一定的参考价值。
#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 << " "; return 0; }
以上是关于AVL树左旋右旋学习总结的主要内容,如果未能解决你的问题,请参考以下文章