1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn=30; int n,nums[maxn]; struct Node{ int v,h; Node *left,*right; Node(int v=0,int h=1,Node* l=NULL,Node* r=NULL):v(v),h(h),left(l),right(r){} }; Node* root=NULL; int getHeight(Node* root){ if (root==NULL) return 0; return root->h; } void updateHeight(Node* &root){ root->h=max(getHeight(root->left),getHeight(root->right))+1; } int getBF(Node* root){ return getHeight(root->left)-getHeight(root->right); } 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); updateHeight(temp); root=temp; }
void insert(Node* &root,int x){ if(root==NULL){ root=new Node(x); return; }else if(root->v>x){ insert(root->left,x); updateHeight(root); if(getBF(root)==2){ if(getBF(root->left)==1){ R(root); }else if(getBF(root->left)==-1){ L(root->left); R(root); } } } else{ insert(root->right,x); updateHeight(root); if(getBF(root)==-2){ if(getBF(root->right)==-1){ L(root); } else if(getBF(root->right)==1){ R(root->right); L(root); } } } } int main(){ scanf("%d",&n); int x; for(int i=0;i<n;i++) { scanf("%d",&x); insert(root,x); } printf("%d",root->v); return 0; }
|