PAT1066(AVL)

来源:互联网 发布:快手绝世的容颜淘宝店 编辑:程序博客网 时间:2024/06/13 23:09
单旋转,只需改变K1,K2的指针域<img src="http://img.blog.csdn.net/20131029223808078?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdmVzcGVyMzA1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />双旋转,进行两次旋转。如图,先进行一次左单旋转,在进行一次右单旋转即可,改变的只是K1、K2、K3的指针域。<img src="http://img.blog.csdn.net/20131029223850468?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdmVzcGVyMzA1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" alt="" />#include<stdio.h>#include<math.h>#include<algorithm>using namespace std;struct node{struct node* left;struct node* right;int value;int height;};int getheight(node *p)//获取树高 {if(p==NULL)return -1;elsereturn p->height;}bool balance(node *p)//判断是否为AVL树 {return abs(getheight(p->left)-getheight(p->right))<2;}node* rotate_LL(node *p)//右单旋转 {node *tmp=p->left;p->left=tmp->right;tmp->right=p;p->height=max(getheight(p->left),getheight(p->right))+1;tmp->height=max(getheight(tmp->left),getheight(tmp->right))+1;return tmp;}node* rotate_RR(node *p)//左单旋转 {node *tmp=p->right;p->right=tmp->left;tmp->left=p;p->height=max(getheight(p->left),getheight(p->right))+1;tmp->height=max(getheight(tmp->left),getheight(tmp->right))+1;return tmp;}node* rotate_LR(node *p)//双旋转 {p->left=rotate_RR(p->left);node *tmp=rotate_LL(p);return tmp;}node* rotate_RL(node *p)//双旋转 {p->right=rotate_LL(p->right);node *tmp=rotate_RR(p);return tmp;}node* insert(node *&root,int x){if(root!=NULL){if(root->value>x){root->left=insert(root->left,x);if(!balance(root)){if(x>root->left->value)//判断作哪种调整 root=rotate_LR(root);elseroot=rotate_LL(root);}}else{root->right=insert(root->right,x);if(!balance(root)){if(x<root->right->value)root=rotate_RL(root);elseroot=rotate_RR(root);}}}else{root=new node;root->height=0;root->left=NULL;root->right=NULL;root->value=x;}root->height=max(getheight(root->left),getheight(root->right))+1;return root;}void print(node *root){if(root!=NULL){print(root->left);printf("%d ",root->value);print(root->right);}}int main(){int n;int x;//freopen("in.txt","r",stdin);node *root=NULL;scanf("%d",&n);for(int i=0;i<n;i++){scanf("%d",&x);root=insert(root,x);}printf("%d\n",root->value);//print(root);return 0;}

0 0
原创粉丝点击