Small code learns 4 kinds of cases of AVL trees with alphabet notation

Source: Internet
Author: User

   /******************  Environment:http://anycodes.cn/zh/ avl   with high label      Red and black trees   more color tags  http://blog.csdn.net/whucyl/article/details/17289841  we always take abc 3 as an example.   After inserting an element c is always unbalanced  LL RR  simpler     after Exchange C or out of the  LR RL  unified sentence is    c always put forward to exchange the subtree, to turn over to do the eldest. &NBSP;LL&NBSP;LR and &NBSP;RR&NBSP;RL are symmetrical 4 cases written in the first 2 kinds can be written after 2 kinds of  ******************/  #ifndef  head_h_# define head_h_#include <stdio.h> #include  <stdlib.h> #define  n 15typedef  int ElementType;typedef struct AvlNode         node of the       // avl tree {elementtype data;struct avlnode *left;            //  left child struct avlnode *right;           //  right child Int height;} *position,*avltree; Avltree makeeMpty (avltree t); Position find (elementtype x,avltree t); Position findmin (avltree t); Position findmax (avltree t); Avltree  insert (elementtype x,avltree t); Avltree  delete (elementtype x,avltree t); Elementtype retrieve (position p); Void display (avltree t); #endif  /* HEAD_H_  */ /* *    initializes the AVL tree  */avltree makeempty (avltree t) {if ( T !=  null) {makeempty (t->left); Makeempty (t->right); free (T);} Return null;} /* *  find   can be done like a normal binary search tree, so it consumes O (log n) time because the AVL tree is always balanced.  *  does not require special preparation, the structure of the tree is not changed by the search. (This is in contrast to the extension tree lookup, which changes the tree structure because of the lookup.) )  */position find (elementtype x,avltree t) {if (t == null) return NULL;if (x  < t->data) Return find (x,t->left); Else if (X > t->data) return  find (x,t->right);else            return  t;/*/Recursive left walk   right walk   either can't find or return the found T node/*/}/* *    FindMax,FindMin  find maximum and minimum values, *    No special     This is recursive or loop to find the bottom right corner and the leftmost lower one   */position findmin (avltree t) {if (t == null)          return null;if ( t->left == null) return t;else             return findmin (t->left);} Position findmax (avltree t) {if (t != null)     { while (T->right  != null)  t=t->right;   }return t;} /* *   returns the height of the node  */static int height (position p) {if (p == null) return  -1;else     return p->height;} Static int max (INT&NBSP;H1,INT&NBSP;H2) {return h1 > h2 ?h1:h2;} /* *   This function is used for K2 only one left child'sSingle rotation, *   rotates between K2 and its left child, *   update height, returns the new root node     frist:                   K2          K1    K2R     K1L   K1R         then:               K1            k1l       k2               k1r      k2r  */ static position  singlerotatewithleft (POSITION&NBSP;K2)     /*/ ll rotation/*/{position k1;k1=k2- >left;k2->left=k1->right;k1->right=k2;/*/  because the height of the left and right child is compared, the height of the parent node is added 1/*/k2->height=max ( Height (k2->left), HeiGht (K2->right))  + 1;k1->height=max (height (k1->left), height (k2->right))  + 1; RETURN&NBSP;K1;} /* *   This function is used to K1 only one right child's single rotation, *   between K1 and its right child rotates, *   update height, returning the new root node   frist:             k1            K1L       K2               k2l      k2r  then:                   K2              K1       K2R       K1L        k2l  */static position singlerotatewithright (POSITION&NBSP;K1)   /*/ &NBSP;RR Rotate/*The position of the/{position k2;k2=k1->right;k1->right=k2->left;k2->left=k1; /* node has changed,  to update the height value of the node */ K1->height=max (height (k1->left), height (k1->right))  + 1;k2->height=max (height (k2->left ), Height (k2->right))  + 1;return k2;} /* *  This function is used when   if &NBSP;K3 has a left child, and  *  its left child has a right child, perform this double rotation  *  update height, return the new root node     first:               k1        K2              K1RK2L         K3                K3L     K3R    then:                    k3          k2                k1k2l            K3L      K3R          k1r */static position doublerotateleft (Position &NBSP;K3)     /*/ lr rotate/*/{/*/in  k3  left child, perform right single rotation/*/k3->left= Singlerotatewithright (k3->left)/*/ rr rotation/*//*/   k3    left single rotation/*/return  Singlerotatewithleft (K3);          /*/ ll rotation/*/}/* *   This function is used when   if &NBSP;K4 has a right child, and  *  it's right child has left child again, perform this double rotation  *  update height, return the new root node     first:                k1           K1L      K2                 K4   K2R              k4L  K4R   then:                    K4           K1                 K2K1L           K4L       k4r         k2r   */static  position doublerotateright (POSITION&NBSP;K4)     /*/ rl rotation/*/{/*/in  k4   Right child, perform left single rotation/*/k4->right = singlerotatewithleft (k4->right);/*/  to  k4    Right single rotation/*/return singlerotatewithright (K4);} /* *   to the AVL tree insert the given value into the tree as if it were an unbalanced two-fork lookup tree, *  The bottom-up to the root node, which is rotated on all nodes that become unbalanced during insertion.  *   because there are up to 1.5 times log n nodes on the way back to the root node, and each AVL rotation consumes a constant amount of time, *   insert processing consumes an overall O (log n )   time.                               X < CUR                           X > CUR                        T                                         T                      x   x                                     X   X                    LL    LR                                RL          &NBSP;&NBSP;RR&NBSP;*/&NBSP;&NBSP;/*/4 Basic Exchange Sub-tree mode   write well    following into the key/*/avltree  insert ( elementtype x,avltree t) {/*/If T does not exist, create a node tree/*/if (t == null) {t =  (AvlTree) malloc ( sizeof (Struct avlnode)); {t->data = x; t->height = 0; T->left = t->right = null;}} /*/  if the element to be inserted is less than the current element/*/else if (x < t->data) {/*/recursively inserts/*/t->left=insert (x,t->left); */After inserting elements, if  T  's Supi right subtree height   difference is  2, that is, does not meet the &NBSP;AVL balance characteristics, need to adjust/*/if (Height (t->left)  -  Height (t->right)  == 2) {/*/inserts x to the left of T->left, just   left single rotation/*/if (x < t->left-> Data) T = singlerotatewithleft (T);        /*/ ll rotation/*/else/*/  x  inserted to the right of the t->left, the left double rotation/*/t =  doublerotateleft (T) is required;     &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//&NBSP;LR rotation/*/}}/*/  If the element to be inserted is greater than the current element/*/else if (x >  T->data) {T->right=insert (x,t->right); if (Height (t->right)  - height (t->left)  == &NBSP;2) {if (x > t->right->data) t = singlerotatewithright (T);      /*/RR  Rotary/*/elset =  doublerotateright (T);       &NBSP;&NBSP;/*/RL swivel/*/}}t->height=max (height (t->left), height (t->right))  + 1;return t;} /* *   AVL adjustments for individual nodes                                t                        TL               tr                   tll   tlr                           X                      1.LL           2.lr                                                                T                       TL               TR                                     TLL   TLR                                                        X                                          3.RL           4.RR                   */avltree rotate (avltree t) {if (Height (t->left)  - height (T-> right) { == 2) {if (Height (t->left->left)  >= height (t->left->right)) T =  singlerotatewithleft (t);   /*/ll rotation/*/elset =  doublerotateleft (t);   &NBSP;&NBSP;&NBSP;/*/&NBSP;LR Rotation/*/}if (Height (t->right)  - height (t->left)  == 2) {if ( Height (t->right->right)   >= height (T->right->left)) t = singlerotatewithright (T); &NBSP;&NBSP;/*/&NBSP;RR rotation/*/ Elset =  doublerotateright (T);      /*/ rl rotation/*/}return t;} /* *  first locates the node to be deleted, then replaces the node with the leftmost child of the right child of that node, *  and resizes the subtree that is the root of the node as the AVL tree, with the exact adjustment method similar to inserting the data  *  The removal process consumes O (log n)   time as a whole.  */avltree  delete (elementtype x,avltree t) {if (t == null) return NULL; if (t->data == x)            /*/the  x to delete   equals the current node element/*/{if (t->right == null )   /*/  If the node to be deleted  T  the right child is empty, Delete the/*/{avltree tmp = t; directly T = t->left;free (TMP);} else                 /*   Find the leftmost son of  T->right  instead of  t */{avltree tmp = t->right;while (tmp- >left) tmp=tmp->left; T->The data = tmp->data;/*  is adjusted for the substituted t  that is its byte point */t->right = delete (T->data,T-> right); T->height = max (height (t->left), height (t->right)) +1;} Return t;} Else if (X > t->data)                         /*/to delete  x  greater than the current node element, Look for delete/*/{t->right=delete (x,t->right) in the right subtree of T;} else                                         /*/  to remove  x  less than the current node element, look for delete/*/{t->left=delete (X,t->left) in the left subtree of T;} /* *    Balance  */t->height=max (height (t->left), height (t->right))  + when element is removed  1;if (t->left != null) t->left = rotate (t->left); if (T->right !=  NULL) t->right = rotate (t->right), if (t) t=rotate (t); return t;} /* *  returns the current position of the element  */elementtype retrieve (position p) {return p->data;} /* *  traversal output  LDR  Middle sequence traversal  */void display (avltree t) {static int n=0;if ( null != t) {Display (t->left);p rintf ("[%d] ndata=%d \n", ++n,t->data);D isplay (T-> right);}}  void pointastree (Avltree t,int lay)  {     if (T)       {         pointastree (T->right,lay+1);          for (int i=0;i<lay;i++)  printf ("** ");p rintf ( "%d \n", T->data);          pointastree (T->left,lay+1);      } }int main () {    avltree t=null;     int i;     Int j = 0;    t = makeempty ( NULL );p UTS ("Data preparation  \n ");     for ( i = 0; i < N; i++, j =  (  j + 7 )  % 50)     {/* Insert 15 numbers  */     printf ("j=%d  ", j);         t = insert ( j,  T )     }    puts ("Insert  4 \n");     t = insert ( 4, T );     //printf ("middle order traversal \ n");     //display (T);          pointastree (T,4);    printf ("Delete even value \ n");    for ( i = 0; i < n; i +=  2 )    {   printf ("delelte: %d \n", i);         t = delete ( i, T )    }   printf ("height=%d \n", t >height);    //printf ("middle order traversal \ n");       //display (T);        pointastree (t,4);p UTS ("[1] ndata=0  [] numbers are only used to show how many times a recursive call \ n");     printf (  "min is %d, max is %d\n",  retrieve ( FindMin (  t )  ),     retrieve ( findmax ( T )  )  ) Return exit_ SUCCESS;}


Small code learns 4 kinds of cases of AVL trees with alphabet notation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.