AVTree.h
1 #ifndef My_avltree_h2 #defineMy_avltree_h3typedefintElementType;4 structTreeNode5 {6 ElementType data;7 structTreeNode *Left ;8 structTreeNode *Right ;9 intheight;Ten }; OnetypedefstructTreeNode TreeNode; Atypedef TreeNode *Tree; - - Tree Find (ElementType e,tree t); the Tree Insert (ElementType e,tree t); - Tree Create (); - //int Destroy ();//This is not written ... Write it down yourself. - Tree leftrotate (Tree t); + Tree rightrotate (Tree t); - intHeight (Tree t); + voidShow (Tree t); A #endif
AVLTree.cpp
1#include <stdlib.h>2#include <stdio.h>3#include"AVLTree.h"4 #defineMAX (a) (a) > (b)? ( A):(B))5 Tree Create ()6 {7Tree t= (tree)malloc(sizeof(TreeNode));8 if(null==t)9 {Tenprintf"memory allocation error \ n"); One returnNULL; A } -T->data=0; -t->left=NULL; thet->right=NULL; -t->height=0; - returnT; - } + Tree Find (ElementType e,tree t) - { + if(null==t) A returnNULL; at if(e==t->data) - returnT; - Else if(e>t->data) - returnFind (e,t->Right ); - Else - returnFind (e,t->Left ); in } - intHeight (Tree t) to { + if(null==t) - return-1; the Else * returnT->height; $ }Panax Notoginseng Tree leftrotate (Tree t) - { the + if(null==t) A returnNULL; theTree newtree=t->Right ; +T->right=newtree->Left ; -newtree->left=T; $T->height=max (height (t->left), height (t->right)) +1; $Newtree->height=max (height (newtree->left), height (newtree->right)) +1; - returnNewTree; - } the - Tree rightrotate (Tree t)Wuyi { the if(null==t) - returnNULL; WuTree newtree=t->Left ; -T->left=newtree->Right ; Aboutnewtree->right=T; $T->height=max (height (t->left), height (t->right)) +1; -Newtree->height=max (height (newtree->left), height (newtree->right)) +1; - returnNewTree; - } A + Tree Insert (ElementType e,tree t) the { - if(null==t) $ { theTree first= (tree)malloc(sizeof(TreeNode)); the if(null==First ) the { theprintf"memory allocation error \ n"); - returnNULL; in } thefirst->left=NULL; thefirst->right=NULL; Aboutfirst->height=0; theFirst->data=e; the returnFirst ; the } + if(e==t->data) - { theprintf"element already exists \ n");Bayi returnT; the } the if(e>t->data) - { -T->right=insert (e,t->Right ); the intLeft=height (t->Left ); the intRight=height (t->Right ); - if(right-left==2) the if(e<t->right->data) the { theT->right=rightrotate (t->Right );94t=leftrotate (t); the } the Else thet=leftrotate (t);98 } About Else - {101T->left=insert (e,t->Left );102 intLeft=height (t->Left );104 intRight=height (t->Right );106 if(left-right==2)107 if(e>t->left->data)108 {109T->left=leftrotate (t->Left ); thet=rightrotate (t);111 } the Else113t=rightrotate (t); the } theT->height=max (height (t->left), height (t->right)) +1; the returnT;117 }118 voidShow (Tree t)119 { - if(t==NULL)121 return;122Show (t->Left );123printf"%d",t->data);124Show (t->Right ); the 126 return;127}
Balanced binary search tree/avl two fork tree C implementation