這些性質保證最長路徑不超過最短路徑 2 倍,實現 O(log n) 查找/插入/刪除。
typedef enum { RED, BLACK } Color;
typedef struct Data { int value; } Data;
typedef struct RBNode {
Color color;
Data *data;
struct RBNode *parent, *left, *right;
} RBNode;
typedef struct { RBNode *root; int size; } RBTree;
旋轉保持 BST 中序序列不變,只調整層級關係。
// 右旋:left 成為新父節點,right 下沉為右子
void rotate_right(RBNode *left, RBNode *right) {
right->left = left->right;
if (left->right) left->right->parent = right;
left->right = right;
left->parent = right->parent;
if (right->parent) {
if (right->parent->left == right) right->parent->left = left;
else right->parent->right = left;
}
right->parent = left;
}
// 左旋:對稱
void rotate_left(RBNode *left, RBNode *right) {
left->right = right->left;
if (right->left) right->left->parent = left;
right->left = left;
right->parent = left->parent;
if (left->parent) {
if (left->parent->right == left) left->parent->right = right;
else left->parent->left = right;
}
left->parent = right;
}
insert_fixup:代碼中用 curnode、parent、grandparent 指標巡檢,旋轉後更新根節點指標。
// 中序遍歷:輸出有序序列
void mid_print(RBNode *root, int level) {
if (!root) return;
mid_print(root->left, level+1);
printf("{color=%s, level=%d, val=%d} ",
root->color==RED?"red":"black", level, root->data->value);
mid_print(root->right, level+1);
}
// 計算樹深度
int depth(RBNode *root) {
if (!root) return 0;
int l = depth(root->left), r = depth(root->right);
return (l > r ? l : r) + 1;
}
int main() {
RBTree *tree = calloc(1, sizeof(RBTree));
int vals[] = {12,24,25,9,4,91,2,100,29,888,10,22,5,11,111,7,13,1,99,222,98,17,8,55,44,33,21,77,199,2345,46,49,51,53,54,52,50,48,47,45,43,42,41,40,39,38,37,78,79,80,81,82,83,84,85};
for (int i=0; ivalue = vals[i];
insert(tree, d); // 省略 insert 完整代碼,見上文
}
printf("Tree depth: %d\n", depth(tree->root));
mid_print(tree->root, 0); putchar('\n');
return 0;
}
輸出深度約 7~8(理論上限 2*log2(65)≈12),中序序列嚴格遞增,驗證 BST 性質與紅黑平衡。
刪除比插入複雜得多(雙黑問題、兄弟節點顏色分析、多種旋轉組合)。建議參考《算法導論》第 13 章或成熟庫(如 Linux kernel rbtree.h、glibc __rb_tree)實現。本文專注插入與驗證框架,為完整實現奠基。