第一棵平衡二叉查找樹被稱為 AVL 樹,以發現者 Adelson-Velskii 與 Landis 命名。它充分體現了平衡二叉查找樹中使用的各種思想——本質上就是帶有附加平衡條件的二叉查找樹。
任何平衡條件都必須易於維護,並確保樹的深度為 O(logN)。最直觀的想法是要求左右子樹高度相同,但這要求太嚴格,插入時維持平衡非常困難。AVL 樹在這方面找到了一個良好的折中點。
1、它是一棵空樹,或其左右子樹高度差的絕對值不超過 1;
2、左右子樹都是平衡二叉樹。
以下用 C++ 實作平衡二叉樹的插入與刪除操作(查詢未具體實作,讀者可自行補充),內容都在程式碼裡。
#include<iostream>
using std::ostream;
class AVLTreeNode
{
private:
int value;
AVLTreeNode* lchild;
AVLTreeNode* rchild;
AVLTreeNode* parent;
friend class AVLTree;
friend ostream& operator<<(ostream& os,const AVLTree&);
public:
AVLTreeNode();
~AVLTreeNode();
};
class AVLTree
{
private:
AVLTreeNode* root;
public:
AVLTree();
~AVLTree();
void insert(int data);
void insert(int datas[],int num);
void remove(int);
void remove(int[],int);
AVLTreeNode* getRoot();
private:
void rightRotate(AVLTreeNode*); //右旋
void leftRotate(AVLTreeNode*); //左旋
bool check_tree(AVLTreeNode*);
int getHeight(AVLTreeNode*);
void insertUpdate(AVLTreeNode*,int); //插入後調整
void removeUpdate(AVLTreeNode*,int); //刪除後調整
friend ostream& operator<<(ostream& os,const AVLTree&);
};
插入後,可能影響從插入點到根這條路徑上某個節點的平衡,因此需要向上找到第一個不平衡節點並對其調整:
void AVLTree::insert(int data)
{
if(!root) //空樹
{
root=new AVLTreeNode;
root->parent=NULL;
root->lchild=root->rchild=NULL;
root->value=data;
}
else
{
AVLTreeNode* p=root;//指向被插入節點的父節點
AVLTreeNode* temp=data>p->value?p->rchild:p->lchild;
while(temp)
{
p=temp;
temp=data>p->value?p->rchild:p->lchild; //值相同放左邊
}
AVLTreeNode* newNode=new AVLTreeNode;
newNode->rchild=newNode->lchild=NULL;
newNode->parent=p;
newNode->value=data;
if(data>p->value)
p->rchild=newNode;
else
p->lchild=newNode;
/*向上找到第一個需要調整的節點*/
p=p->parent;
int v;
if(p)
v=abs(getHeight(p->lchild)-getHeight(p->rchild));
while(p&&v<=1)
{
p=p->parent;
if(p)
v=abs(getHeight(p->lchild)-getHeight(p->rchild));
}
//若發現受影響節點,對第一個不平衡點做調整
if(p)
{
insertUpdate(p,data);
}
}
}
其中 node 代表從插入點向上找到的第一個不平衡點,透過左旋、右旋即可恢復 AVL 性質。測試資料的顯示量可視需要調整,插入與刪除方法中亦保留了測試列印,讀者可自行修改。