A1066 Root of AVL Tree (25分)

    技术2026-02-22  6

    #include<cstdio> #include<stdlib.h> #include<iostream> #include<cstring> #include<algorithm> #include<cmath> #include<set> #include<vector> #include<map> #include<queue> #include<stack> #include<string> using namespace std; //A1066 const int maxn=20; struct node{ int data; int height; node *left; node *right; }; int data[maxn]; node* newNode(int data){ node *root=new node; root->data=data; root->left=root->right=NULL; root->height=1; return root; } int getHeight(node* root){ if(root==NULL)return 0; else return root->height; } int getAVLFactor(node* root){//一定要使用getHeight,万一节点是null直接用指针获取不到节点的高 int result=getHeight(root->left)-getHeight(root->right); // cout<<"factor="<<result<<endl; return result; } void updateHeight(node* root){ root->height= max(getHeight(root->left),getHeight(root->right))+1; } void R(node* &root){ node* temp=root->left; root->left=temp->right; temp->right=root; //从下到上更新节点的高度 updateHeight(root); updateHeight(temp); root=temp; } void L(node* &root){ node* temp=root->right; root->right=temp->left; temp->left=root; updateHeight(root);//如果返回int的话,直接调用里面就没有更新操作了 updateHeight(temp); root=temp; } void insert(node* &root,int data){ if(root==NULL){ root=newNode(data); // cout<<"root.data="<<data<<endl; return; } if(data<root->data){//应该插入左子树 insert(root->left,data); updateHeight(root); // cout<<"getAVLFactor(root)"<<getAVLFactor(root)<<endl; if(getAVLFactor(root)==2){ if(getAVLFactor(root->left)==1){//LL R(root); }else if(getAVLFactor(root->left)==-1){//LR L(root->left); R(root); } } }else{ insert(root->right,data); updateHeight(root); if(getAVLFactor(root)==-2){ if(getAVLFactor(root->right)==-1){//RR L(root); }else if(getAVLFactor(root->right)==1){//RL R(root->right); L(root); } } } } int main() { int n; scanf("%d",&n); node *root=NULL; int data; for(int i=0;i<n;i++){ scanf("%d",&data); insert(root,data); } printf("%d",root->data); return 0; }

     

    Processed: 0.012, SQL: 9