标签:
//AVTree.h
1 #ifndef MY_AVLTREE_H 2 #define MY_AVLTREE_H 3 typedef int ElementType; 4 struct TreeNode 5 { 6 ElementType data; 7 struct TreeNode *left; 8 struct TreeNode *right; 9 int height; 10 }; 11 typedef struct TreeNode TreeNode; 12 typedef TreeNode *Tree; 13 14 Tree Find(ElementType e,Tree t); 15 Tree Insert(ElementType e,Tree t); 16 Tree Create(); 17 //int Destroy();//这个没写。。。自己写下吧 18 Tree LeftRotate(Tree t); 19 Tree RightRotate(Tree t); 20 int Height(Tree t); 21 void Show(Tree t); 22 #endif
//AVLTree.cpp
1 #include <stdlib.h> 2 #include <stdio.h> 3 #include "AVLTree.h" 4 #define MAX(a,b) ((a)>(b)?(a):(b)) 5 Tree Create() 6 { 7 Tree t=(Tree)malloc(sizeof(TreeNode)); 8 if(NULL==t) 9 { 10 printf("内存分配错误\n"); 11 return NULL; 12 } 13 t->data=0; 14 t->left=NULL; 15 t->right=NULL; 16 t->height=0; 17 return t; 18 } 19 Tree Find(ElementType e,Tree t) 20 { 21 if(NULL==t) 22 return NULL; 23 if(e==t->data) 24 return t; 25 else if(e>t->data) 26 return Find(e,t->right); 27 else 28 return Find(e,t->left); 29 } 30 int Height(Tree t) 31 { 32 if(NULL==t) 33 return -1; 34 else 35 return t->height; 36 } 37 Tree LeftRotate(Tree t) 38 { 39 40 if(NULL==t) 41 return NULL; 42 Tree newtree=t->right; 43 t->right=newtree->left; 44 newtree->left=t; 45 t->height=MAX(Height(t->left),Height(t->right))+1; 46 newtree->height=MAX(Height(newtree->left),Height(newtree->right))+1; 47 return newtree; 48 } 49 50 Tree RightRotate(Tree t) 51 { 52 if(NULL==t) 53 return NULL; 54 Tree newtree=t->left; 55 t->left=newtree->right; 56 newtree->right=t; 57 t->height=MAX(Height(t->left),Height(t->right))+1; 58 newtree->height=MAX(Height(newtree->left),Height(newtree->right))+1; 59 return newtree; 60 } 61 62 Tree Insert(ElementType e,Tree t) 63 { 64 if(NULL==t) 65 { 66 Tree first=(Tree)malloc(sizeof(TreeNode)); 67 if(NULL==first) 68 { 69 printf("内存分配错误\n"); 70 return NULL; 71 } 72 first->left=NULL; 73 first->right=NULL; 74 first->height=0; 75 first->data=e; 76 return first; 77 } 78 if(e==t->data) 79 { 80 printf("元素已存在\n"); 81 return t; 82 } 83 if(e>t->data) 84 { 85 t->right=Insert(e,t->right); 86 int left=Height(t->left); 88 int right=Height(t->right); 90 if(right-left==2) 91 if (e<t->right->data) 92 { 93 t->right=RightRotate(t->right); 94 t=LeftRotate(t); 95 } 96 else 97 t=LeftRotate(t); 98 } 99 else 100 { 101 t->left=Insert(e,t->left); 102 int left=Height(t->left); 104 int right=Height(t->right); 106 if(left-right==2) 107 if (e>t->left->data) 108 { 109 t->left=LeftRotate(t->left); 110 t=RightRotate(t); 111 } 112 else 113 t=RightRotate(t); 114 } 115 t->height=MAX(Height(t->left),Height(t->right))+1; 116 return t; 117 } 118 void Show(Tree t) 119 { 120 if(t==NULL) 121 return; 122 Show(t->left); 123 printf("%d ",t->data); 124 Show(t->right); 125 126 return; 127 }
标签:
原文地址:http://www.cnblogs.com/NickCarter/p/5723847.html