关键:
1.每插入一个节点或更换节点位置都要更新一次其根节点的高度
2.判断不平衡的条件,左右子树高度差为2
先看avlInsert()函数里的大框架会比较好理解
#include<stdio.h> #include<stdlib.h> typedef struct tree { int data; int height; struct tree* lchild; struct tree* rchild; }treenode,tree; int Height(tree* node) { if(node) return node->height; else return 0; } int max(int a,int b) { if(a>b) return a; else return b; } void llRotation(tree* node,tree** T) { tree* temp = node->lchild; node->lchild = temp->rchild ; temp->rchild = node; *T = temp; temp->height = max(Height(temp->lchild ),Height(temp->rchild))+1; node->height = max(Height(node->lchild),Height(node->rchild))+1; return ; } void rrRotation(tree* node,tree** T) { tree* temp = node->rchild; node->rchild = temp->lchild ; temp->lchild = node; *T = temp; temp->height = max(Height(temp->lchild ),Height(temp->rchild))+1; node->height = max(Height(node->lchild),Height(node->rchild))+1; return ; } void avlInsert(tree** T,int data) { if(*T==NULL) { *T = (tree*)malloc(sizeof(tree)); (*T)->data = data; (*T)->lchild = NULL; (*T)->rchild = NULL; } else if((*T)->data>data) { avlInsert(&(*T)->lchild,data); int lheight = Height((*T)->lchild); int rheight = Height((*T)->rchild); //判断高度差 if(lheight-rheight==2) { if((*T)->lchild->data>data) //LL调整 llRotation(*T,T); else //LR调整 rrRotation((*T)->lchild,&(*T)->lchild); llRotation(*T,&(*T)); } } else { avlInsert(&(*T)->rchild,data); int lheight = Height((*T)->lchild); int rheight = Height((*T)->rchild); //判断高度差 if(rheight-lheight==2) { if((*T)->rchild->data>data) //RL调整 { llRotation((*T)->rchild,&(*T)->rchild); rrRotation(*T,&(*T)); } else //RR调整 rrRotation(*T,&(*T)); } } (*T)->height = max(Height((*T)->lchild),Height((*T)->rchild))+1; } void Preorder(tree* T)//前序遍历看看对不对 { if(T) { printf("%d ",T->data ); Preorder(T->lchild ); Preorder(T->rchild ); } return ; } int main() { tree* T; int i; int a[5] = {1,2,3,4,5}; for(i = 0;i<5;i++) avlInsert(&T,a[i]); Preorder(T); printf("\n"); return 0; }