Code:
#include <iostream> #include <cstdio> #include <cmath> #include <stdlib.h> #define MAX (b) (a) > (b)? (a):(B)) using namespace std;struct node{int value; node* l; node* R; int bf;//Zuozi Height-right subtree height void init (int v) {value=v; L=null; R=null; bf=0; }};int Abs (int a) {return a>=0?a:-a;} int GETBF (node* p) {if (p = = NULL) return-1; return P->BF;} BOOL Isbalanced (node* p) {return Abs (GETBF (p->l)-GETBF (P->r)) < 2;} node* LL (node* p) {node* child = p->l; P->l = child->r; Child->r = p; P->BF = Max (GETBF (p->l), GETBF (p->r)) + 1; CHILD->BF = Max (GETBF (child->l), GETBF (child->r)) + 1; return child;} node* RR (node* p) {node* child = p->r; P->r= child->l; Child->l = p; P->BF = Max (GETBF (p->l), GETBF (p->r)) + 1; CHILD->BF = Max (GETBF (child->l), GETBF (child->r)) + 1; return child;} node* LR (node* p) {node* child= p->l; P->l = RR (child); Return LL (p);} node* RL (node* p) {node* child = p->r; P->r =ll (child); Return RR (p);} node* Insert (node* p,int x) {if (p!=null) {if (X>p->value)//r {p->r= Insert (p-> R,X); if (!isbalanced (p)) {if (x> p->r->value)//r-r p = RR (p); Else//r-l P=RL (P); }} else//l {p->l= Insert (p->l,x); if (!isbalanced (p)) {if (x > P->l->value)//l-r p = LR (p); Else//l-l p = LL (p); }}}} else {p= (node*) malloc (sizeof (Node)); (*p). Init (x); } P->BF = Max (GETBF (p->l), GETBF (p->r)) + 1; return p;} /*void printtree (node* root)//first-order traversal AVL tree {if (root! = NULL) {cout<<root->value<< "--"; Printtree (ROOT->L); Printtree (ROOT->R); }}*/int Main () {int n; while (scanf ("%d", &n) ==1) {node* root=null; int x; for (int i=0; i<n; i++) {scanf ("%d", &x); Root=insert (ROOT,X); } printf ("%d\n", Root->value); Printtree (root); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Pat (A) 1066. Root of AVL Tree