typedef enum { EH = 0, LH = 1, RH = -1 } BalanceFactor;
typedef enum { FALSE = 0, TRUE = 1 } Bool;
typedef int ElemType;
typedef struct BSTNode {
ElemType key;
int bf; // 平衡因子
struct BSTNode *lchild, *rchild, *parent;
} BSTNode, *BSTree;
引入 parent 指標,支援非遞歸回溯調整。
searchAVL非遞歸下降,返回是否找到及父節點位置。
BSTNode* minNode(BSTNode* root) { while (root->lchild) root = root->lchild; return root; }
BSTNode* maxNode(BSTNode* root) { while (root->rchild) root = root->rchild; return root; }
BSTNode* preNode(BSTNode* t) { // 中序前驅
if (t->lchild) return maxNode(t->lchild);
while (t->parent && t != t->parent->rchild) t = t->parent;
return t->parent;
}
BSTNode* nextNode(BSTNode* t) { // 中序後繼
if (t->rchild) return minNode(t->rchild);
while (t->parent && t != t->parent->lchild) t = t->parent;
return t->parent;
}
leftbalance處理 LL / LR 兩種情況,更新 bf、parent、祖先指向,返回新子樹根。
rightbalance對稱處理 RR / RL。
insertNodebf=EH。bf:bf 從 EH→LH/RH 繼續向上。bf 從 LH/RH→EH 停止回溯。bf 從 LH→LH 或 RH→RH 觸發旋轉,調整後結束。deleteNodebf:bf 從 LH/RH→EH 繼續向上。bf 從 EH→LH/RH 停止。bf 從 LH→RH 或 RH→LH 觸發旋轉,調整後結束。
int data[] = {1,5,7,4,3,2,11,9,10,100};
BSTNode* root = createAVL(data, 10);
InOrderTraverse(root); // 中序輸出有序
PreOrderTraverse(root); // 先序輸出樹結構
root = deleteNode(5, root); // 連續刪除驗證平衡維護
root = deleteNode(3, root);
root = deleteNode(1, root);
root = deleteNode(7, root);
root = deleteNode(4, root);
root = deleteNode(2, root);
destroyAVL(root);
createAVL/destroyAVL 成對使用,無洩漏。查找、插入、刪除均為 O(log n),嚴格平衡保證最壞情況性能。