概念
AVL樹是高度平衡的二叉排序樹。
它的特點是:AVL樹中任何節點的左右子樹的高度差(平衡因子)的絕對值不大於1。
它需要每次在平衡因子不爲0,-1,1時進行調整,使樹的再次平衡。從而達到高效的查找。
點擊這裏:AVL的詳細介紹
C++代碼實現:
AVL樹是特殊的二叉排序樹,它的實現除了插入、刪除操作外,其他的和平衡排序樹相同,這裏就不再實現,這裏給出插入的算法。
#include <iostream>
#include <algorithm> // max(a, b)
using namespace std;
typedef struct AVLTreeNode
{
int key; // 結點的關鍵字
int height; // 樹的高度
AVLTreeNode *lChild, *rChild; // 左右孩子
}*AVLTree;
// 樹高
int Height(const AVLTree &T)
{
return T ? T->height : 0;
}
// LL旋轉
void LeftLeftRotation(AVLTree &T)
{
AVLTree lT = T->lChild;
T->lChild = lT->rChild;
lT->rChild = T;
T->height = max(Height(T->lChild), Height(T->rChild)) + 1;
lT->height = max(Height(lT->lChild), Height(lT->rChild)) + 1;
T = lT;
}
// RR旋轉
void RightRightRotation(AVLTree &T)
{
AVLTree rT = T->rChild;
T->rChild = rT->lChild;
rT->lChild = T;
T->height = max(Height(T->lChild), Height(T->rChild)) + 1;
rT->height = max(Height(rT->lChild), Height(rT->rChild)) + 1;
T = rT;
}
// LR旋轉
void LeftRightRotation(AVLTree &T)
{
RightRightRotation(T->lChild);
LeftLeftRotation(T);
}
// RL旋轉
void RightLeftRotation(AVLTree &T)
{
LeftLeftRotation(T->rChild);
RightRightRotation(T);
}
// 插入結點
void Insert(AVLTree &T, const int &key)
{
if(!T){ // 爲空樹,新建結點作爲根結點
T = new AVLTreeNode;
T->height = 1;
T->key = key;
T->lChild = T->rChild = NULL;
}
else if(key < T->key){ // key小於根結點關鍵字,則插入到左子樹
Insert(T->lChild, key);
T->height = max(Height(T->lChild), Height(T->rChild)) + 1;
// 如果插入的新結點破壞了平衡,則進行調整
if(2 == Height(T->lChild) - Height(T->rChild)){
if(key < T->lChild->key){
LeftLeftRotation(T);
}
else{
LeftRightRotation(T);
}
}
}
else{ // key大於等於根結點關鍵字,則插入到右子樹
Insert(T->rChild, key);
T->height = max(Height(T->lChild), Height(T->rChild)) + 1;
// 如果插入的新結點破壞了平衡,則進行調整
if(2 == Height(T->rChild) - Height(T->lChild)){
if(key < T->rChild->key){
RightLeftRotation(T);
}
else{
RightRightRotation(T);
}
}
}
}
// 中序遍歷
void InOrderTraverse(const AVLTree &T)
{
if(T){
InOrderTraverse(T->lChild);
cout << T->key << "(" << T->height << ") ";
InOrderTraverse(T->rChild);
}
}
int main()
{
AVLTree T = NULL;
Insert(T, 1);
Insert(T, 3);
Insert(T, 5);
Insert(T, 7);
Insert(T, 9);
InOrderTraverse(T);
cout << endl;
Insert(T, 6);
InOrderTraverse(T);
cout << endl;
Insert(T, 0);
InOrderTraverse(T);
cout << endl;
return 0;
}
運行結果:
所對應的二叉樹: