AVL 模板完整實作,包含節點定義、高度維護、四種旋轉 (LL、RR、LR、RL) 及插入調整邏輯,可直接用於教學或工程參考。
typedef struct AVLTreeNode *AVLTree;
typedef struct AVLTreeNode {
int data;
AVLTree left;
AVLTree right;
int height;
} AVLTreeNode;
int getHeight(AVLTree T) {
return T ? T->height : -1;
}
AVLTree singleLeftRotation(AVLTree A) {
AVLTree B = A->left;
A->left = B->right;
B->right = A;
A->height = max(getHeight(A->left), getHeight(A->right)) + 1;
B->height = max(getHeight(B->left), A->height) + 1;
return B; // 新根節點
}
AVLTree singleRightRotation(AVLTree A) {
AVLTree B = A->right;
A->right = B->left;
B->left = A;
A->height = max(getHeight(A->left), getHeight(A->right)) + 1;
B->height = max(getHeight(B->right), A->height) + 1;
return B;
}
AVLTree doubleLeftRightRotation(AVLTree A) {
A->left = singleRightRotation(A->left); // 先對左子樹右旋
return singleLeftRotation(A); // 再對根左旋
}
AVLTree doubleRightLeftRotation(AVLTree A) {
A->right = singleLeftRotation(A->right); // 先對右子樹左旋
return singleRightRotation(A); // 再對根右旋
}
AVLTree avlInsert(int X, AVLTree T) {
if (!T) { // 空樹:建立新節點
T = (AVLTree)malloc(sizeof(struct AVLTreeNode));
T->data = X;
T->height = 0;
T->left = T->right = NULL;
}
else if (X < T->data) { // 插入左子樹
T->left = avlInsert(X, T->left);
if (getHeight(T->left) - getHeight(T->right) == 2) {
if (X < T->left->data) // LL
T = singleLeftRotation(T);
else // LR
T = doubleLeftRightRotation(T);
}
}
else if (X > T->data) { // 插入右子樹
T->right = avlInsert(X, T->right);
if (getHeight(T->left) - getHeight(T->right) == -2) {
if (X > T->right->data) // RR
T = singleRightRotation(T);
else // RL
T = doubleRightLeftRotation(T);
}
}
// X == T->data:不重複插入
T->height = max(getHeight(T->left), getHeight(T->right)) + 1;
return T;
}
| 不平衡類型 | 平衡因子 | 插入位置 | 旋轉方式 |
|---|---|---|---|
| LL | +2 | 左子樹的左側 | 左單旋 |
| LR | +2 | 左子樹的右側 | 右單旋(左子) → 左單旋(根) |
| RL | -2 | 右子樹的左側 | 左單旋(右子) → 右單旋(根) |
| RR | -2 | 右子樹的右側 | 右單旋 |