PAT A1066 Root of AVL Tree
建立一颗avl树并输出根节点~
#include<cstdio> #include<algorithm> using namespace std; struct node { int v; int height; node * left; node * right; }; node * newNode (int v) { node * Node=new node; Node->v=v; Node->height=1; Node->left=NULL; Node->right=NULL; return Node; } int getHeight (node * root) { if (root==NULL) return 0; return root->height; } void update (node * &root) { root->height=max(getHeight(root->left),getHeight(root->right))+1; } int getBalance (node * root) { return getHeight(root->left)-getHeight(root->right); } void L (node * &root) { node * temp=root->right; root->right=temp->left; temp->left=root; update(root); update(temp); root=temp; } void R (node * &root) { node * temp=root->left; root->left=temp->right; temp->right=root; update(root); update(temp); root=temp; } void insert (node * &root,int x) { if (root==NULL) { root=newNode(x); return; } if (x<root->v) { insert (root->left,x); update(root); if (getBalance(root)==2) { if (getBalance(root->left)==1) R(root); else if (getBalance(root->left)==-1) { L(root->left); R(root); } } } else { insert (root->right,x); update(root); if (getBalance(root)==-2) { if (getBalance(root->right)==-1) L(root); else if (getBalance(root->right)==1) { R(root->right); L(root); } } } } int main () { int N; scanf ("%d",&N); int x; node * root=NULL; for (int i=0;i<N;i++) { scanf ("%d",&x); insert (root,x); } printf ("%d",root->v); return 0; }