詳解Linux內核紅黑樹算法的實現

轉自:http://blog.csdn.net/npy_lp/article/details/7420689

平衡二叉樹(BalancedBinary Tree或Height-Balanced Tree)又稱AVL樹。它或者是一棵空樹,或者是具有下列性質的二叉樹:它的左子樹和右子樹都是平衡二叉樹,且左子樹和右子樹的深度之差的絕對值不超過1。若將二叉樹上結點的平衡因子BF(BalanceFactor)定義爲該結點的左子樹的深度減去它的右子樹的深度,則平衡二叉樹上所有結點的平衡因子只可能是-1、0和1。(此段定義來自嚴蔚敏的《數據結構(C語言版)》)

    紅黑樹是一種在插入或刪除結點時都需要維持平衡的二叉查找樹,並且每個結點都具有顏色屬性:

    (1)、一個結點要麼是紅色的,要麼是黑色的。

    (2)、根結點是黑色的。

    (3)、如果一個結點是紅色的,那麼它的子結點必須是黑色的,也就是說在沿着從根結點出發的任何路徑上都不會出現兩個連續的紅色結點。

    (4)、從一個結點到一個NULL指針的每條路徑上必須包含相同數目的黑色結點。

 

(此圖片來自維基百科)

    Linux內核紅黑樹的算法都定義在linux-2.6.38.8/include/linux/rbtree.h和linux-2.6.38.8/lib/rbtree.c兩個文件中。

    1、結構體 

  1. struct rb_node  
  2. {  
  3.     unsigned long  rb_parent_color;  
  4. #define RB_RED      0  
  5. #define RB_BLACK    1  
  6.     struct rb_node *rb_right;  
  7.     struct rb_node *rb_left;  
  8. } __attribute__((aligned(sizeof(long))));  

     這裏的巧妙之處是使用成員rb_parent_color同時存儲兩種數據,一是其雙親結點的地址,另一是此結點的着色。__attribute__((aligned(sizeof(long))))屬性保證了紅黑樹中的每個結點的首地址都是32位對齊的(在32位機上),也就是說每個結點首地址的bit[1]和bit[0]都是0,因此就可以使用bit[0]來存儲結點的顏色屬性而不干擾到其雙親結點首地址的存儲。

    操作rb_parent_color的函數: 

  1. #define rb_parent(r)   ((struct rb_node *)((r)->rb_parent_color & ~3))  //獲得其雙親結點的首地址  
  2. #define rb_color(r)   ((r)->rb_parent_color & 1) //獲得顏色屬性  
  3. #define rb_is_red(r)   (!rb_color(r))   //判斷顏色屬性是否爲紅  
  4. #define rb_is_black(r) rb_color(r) //判斷顏色屬性是否爲黑  
  5. #define rb_set_red(r)  do { (r)->rb_parent_color &= ~1; } while (0)  //設置紅色屬性  
  6. #define rb_set_black(r)  do { (r)->rb_parent_color |= 1; } while (0) //設置黑色屬性  
  7.   
  8. static inline void rb_set_parent(struct rb_node *rb, struct rb_node *p)  //設置其雙親結點首地址的函數  
  9. {  
  10.     rb->rb_parent_color = (rb->rb_parent_color & 3) | (unsigned long)p;  
  11. }  
  12. static inline void rb_set_color(struct rb_node *rb, int color) //設置結點顏色屬性的函數  
  13. {  
  14.     rb->rb_parent_color = (rb->rb_parent_color & ~1) | color;  
  15. }  

    初始化新結點: 

  1. static inline void rb_link_node(struct rb_node * node, struct rb_node * parent,  
  2.                 struct rb_node ** rb_link)  
  3. {  
  4.     node->rb_parent_color = (unsigned long )parent;   //設置其雙親結點的首地址(根結點的雙親結點爲NULL),且顏色屬性設爲黑色  
  5.     node->rb_left = node->rb_right = NULL;   //初始化新結點的左右子樹  
  6.   
  7.     *rb_link = node;  //指向新結點  
  8. }  

    指向紅黑樹根結點的指針: 

  1. struct rb_root  
  2. {  
  3.     struct rb_node *rb_node;  
  4. };  
  5.   
  6.   
  7. #define RB_ROOT (struct rb_root) { NULL, }  //初始化指向紅黑樹根結點的指針  
  8. #define rb_entry(ptr, type, member) container_of(ptr, type, member) //用來獲得包含struct rb_node的結構體的首地址  
  9.   
  10. #define RB_EMPTY_ROOT(root) ((root)->rb_node == NULL) //判斷樹是否爲空  
  11. #define RB_EMPTY_NODE(node) (rb_parent(node) == node)  //判斷node的雙親結點是否爲自身  
  12. #define RB_CLEAR_NODE(node) (rb_set_parent(node, node)) //設置雙親結點爲自身  

    2、插入

    首先像二叉查找樹一樣插入一個新結點,然後根據情況作出相應的調整,以使其滿足紅黑樹的顏色屬性(其實質是維持紅黑樹的平衡)。

    函數rb_insert_color使用while循環不斷地判斷雙親結點是否存在,且顏色屬性爲紅色。

    若判斷條件爲真,則分成兩部分執行後續的操作:

    (1)、當雙親結點是祖父結點左子樹的根時,則:

    a、存在叔父結點,且顏色屬性爲紅色。

 

    b、當node是其雙親結點右子樹的根時,則左旋,然後執行第c步。

 

    c、當node是其雙親結點左子樹的根時。

 

    (2)、當雙親結點是祖父結點右子樹的根時的操作與第(1)步大致相同,這裏略過不談。

    若爲假,則始終設置根結點的顏色屬性爲黑色。

 

  1. void rb_insert_color(struct rb_node *node, struct rb_root *root)  
  2. {  
  3.     struct rb_node *parent, *gparent;  
  4.   
  5.     while ((parent = rb_parent(node)) && rb_is_red(parent)) //雙親結點不爲NULL,且顏色屬性爲紅色  
  6.     {  
  7.         gparent = rb_parent(parent); //獲得祖父結點  
  8.   
  9.         if (parent == gparent->rb_left) //雙親結點是祖父結點左子樹的根  
  10.         {  
  11.             {  
  12.                 register struct rb_node *uncle = gparent->rb_right; //獲得叔父結點  
  13.                 if (uncle && rb_is_red(uncle)) //叔父結點存在,且顏色屬性爲紅色  
  14.                 {  
  15.                     rb_set_black(uncle); //設置叔父結點爲黑色  
  16.                     rb_set_black(parent); //設置雙親結點爲黑色  
  17.                     rb_set_red(gparent); //設置祖父結點爲紅色  
  18.                     node = gparent;  //node指向祖父結點   
  19.                     continue//繼續下一個while循環  
  20.                 }  
  21.             }  
  22.   
  23.             if (parent->rb_right == node)  //當node是其雙親結點右子樹的根時  
  24.             {  
  25.                 register struct rb_node *tmp;  
  26.                 __rb_rotate_left(parent, root); //左旋  
  27.                 tmp = parent;  //調整parent和node指針的指向  
  28.                 parent = node;  
  29.                 node = tmp;  
  30.             }  
  31.   
  32.             rb_set_black(parent); //設置雙親結點爲黑色  
  33.             rb_set_red(gparent); //設置祖父結點爲紅色  
  34.             __rb_rotate_right(gparent, root); //右旋  
  35.         } else { // !(parent == gparent->rb_left)  
  36.             {  
  37.                 register struct rb_node *uncle = gparent->rb_left;  
  38.                 if (uncle && rb_is_red(uncle))  
  39.                 {  
  40.                     rb_set_black(uncle);  
  41.                     rb_set_black(parent);  
  42.                     rb_set_red(gparent);  
  43.                     node = gparent;  
  44.                     continue;  
  45.                 }  
  46.             }  
  47.   
  48.             if (parent->rb_left == node)  
  49.             {  
  50.                 register struct rb_node *tmp;  
  51.                 __rb_rotate_right(parent, root);  
  52.                 tmp = parent;  
  53.                 parent = node;  
  54.                 node = tmp;  
  55.             }  
  56.   
  57.             rb_set_black(parent);  
  58.             rb_set_red(gparent);  
  59.             __rb_rotate_left(gparent, root);  
  60.         } //end if (parent == gparent->rb_left)  
  61.     } //end while ((parent = rb_parent(node)) && rb_is_red(parent))  
  62.   
  63.     rb_set_black(root->rb_node);  
  64. }  

    3、刪除

    像二叉查找樹的刪除操作一樣,首先需要找到所需刪除的結點,然後根據該結點左右子樹的有無分爲三種情形:

 

    若node結點的顏色屬性爲黑色,則需要調用__rb_erase_color函數來進行調整。

 

  1. void rb_erase(struct rb_node *node, struct rb_root *root)  
  2. {  
  3.     struct rb_node *child, *parent;  
  4.     int color;  
  5.   
  6.     if (!node->rb_left) //刪除結點無左子樹  
  7.         child = node->rb_right;  
  8.     else if (!node->rb_right) //刪除結點無右子樹  
  9.         child = node->rb_left;  
  10.     else //左右子樹都有  
  11.     {  
  12.         struct rb_node *old = node, *left;  
  13.   
  14.         node = node->rb_right;  
  15.         while ((left = node->rb_left) != NULL)  
  16.             node = left;  
  17.   
  18.         if (rb_parent(old)) {  
  19.             if (rb_parent(old)->rb_left == old)  
  20.                 rb_parent(old)->rb_left = node;  
  21.             else  
  22.                 rb_parent(old)->rb_right = node;  
  23.         } else  
  24.             root->rb_node = node;  
  25.   
  26.         child = node->rb_right;  
  27.         parent = rb_parent(node);  
  28.         color = rb_color(node);  
  29.   
  30.         if (parent == old) {  
  31.             parent = node;  
  32.         } else {  
  33.             if (child)  
  34.                 rb_set_parent(child, parent);  
  35.             parent->rb_left = child;  
  36.   
  37.             node->rb_right = old->rb_right;  
  38.             rb_set_parent(old->rb_right, node);  
  39.         }  
  40.   
  41.         node->rb_parent_color = old->rb_parent_color;  
  42.         node->rb_left = old->rb_left;  
  43.         rb_set_parent(old->rb_left, node);  
  44.   
  45.         goto color;  
  46.     }  //end else  
  47.   
  48.     parent = rb_parent(node); //獲得刪除結點的雙親結點  
  49.     color = rb_color(node); //獲取刪除結點的顏色屬性  
  50.   
  51.     if (child)  
  52.         rb_set_parent(child, parent);  
  53.     if (parent)  
  54.     {  
  55.         if (parent->rb_left == node)  
  56.             parent->rb_left = child;  
  57.         else  
  58.             parent->rb_right = child;  
  59.     }  
  60.     else  
  61.         root->rb_node = child;  
  62.   
  63.  color:  
  64.     if (color == RB_BLACK) //如果刪除結點的顏色屬性爲黑色,則需調用__rb_erase_color函數來進行調整  
  65.         __rb_erase_color(child, parent, root);  
  66. }  

    4、遍歷

    rb_first和rb_next函數可組成中序遍歷,即以升序遍歷紅黑樹中的所有結點。 

  1. struct rb_node *rb_first(const struct rb_root *root)  
  2. {  
  3.     struct rb_node  *n;  
  4.   
  5.     n = root->rb_node;  
  6.     if (!n)  
  7.         return NULL;  
  8.     while (n->rb_left)  
  9.         n = n->rb_left;  
  10.     return n;  
  11. }  
  12.   
  13. struct rb_node *rb_next(const struct rb_node *node)  
  14. {  
  15.     struct rb_node *parent;  
  16.   
  17.     if (rb_parent(node) == node)  
  18.         return NULL;  
  19.   
  20.     /* If we have a right-hand child, go down and then left as far 
  21.        as we can. */  
  22.     if (node->rb_right) {  
  23.         node = node->rb_right;   
  24.         while (node->rb_left)  
  25.             node=node->rb_left;  
  26.         return (struct rb_node *)node;  
  27.     }  
  28.   
  29.     /* No right-hand children.  Everything down and left is 
  30.        smaller than us, so any 'next' node must be in the general 
  31.        direction of our parent. Go up the tree; any time the 
  32.        ancestor is a right-hand child of its parent, keep going 
  33.        up. First time it's a left-hand child of its parent, said 
  34.        parent is our 'next' node. */  
  35.     while ((parent = rb_parent(node)) && node == parent->rb_right)  
  36.         node = parent;  
  37.   
  38.     return parent;  
  39. }  

    5、在應用程序中使用

    Linux內核中紅黑樹算法的實現非常通用、巧妙,而且免費又開源,因此完全可以把它運用到自己的應用程序中。

    (1)、從內核中拷貝源文件: 

  1. $ mkdir redblack  
  2. $ cd redblack/  
  3. $ cp ../linux-2.6.38.8/lib/rbtree.c .  
  4. $ cp ../linux-2.6.38.8/include/linux/rbtree.h .  

    (2)、修改源文件:

    a、C文件rbtree.c

    修改包含頭文件的代碼 

  1. //刪除以下兩行代碼  
  2. #include <linux/rbtree.h>  
  3. #include <linux/module.h>  
  4. //新增以下代碼,即包含當前目錄中的頭文件rbtree.h  
  5. #include "rbtree.h"  

    刪除所有的EXPORT_SYMBOL宏 

  1. EXPORT_SYMBOL(rb_insert_color);  
  2. EXPORT_SYMBOL(rb_erase);  
  3. EXPORT_SYMBOL(rb_augment_insert);  
  4. EXPORT_SYMBOL(rb_augment_erase_begin);  
  5. EXPORT_SYMBOL(rb_augment_erase_end);  
  6. EXPORT_SYMBOL(rb_first);  
  7. EXPORT_SYMBOL(rb_last);  
  8. EXPORT_SYMBOL(rb_next);  
  9. EXPORT_SYMBOL(rb_prev);  
  10. EXPORT_SYMBOL(rb_replace_node);  

    b、頭文件rbtree.h

    刪除包含頭文件的代碼,並添加三個宏定義 

  1. //刪除以下兩行代碼  
  2. #include <linux/kernel.h>  
  3. #include <linux/stddef.h>  
  4.   
  5. /* linux-2.6.38.8/include/linux/stddef.h */  
  6. #undef NULL  
  7. #if defined(__cplusplus)  
  8. #define NULL 0  
  9. #else  
  10. #define NULL ((void *)0)  
  11. #endif  
  12.   
  13. /* linux-2.6.38.8/include/linux/stddef.h */  
  14. #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)  
  15.   
  16. /* linux-2.6.38.8/include/linux/kernel.h */  
  17. #define container_of(ptr, type, member) ({          \  
  18.     const typeof( ((type *)0)->member ) *__mptr = (ptr); \  
  19.     (type *)( (char *)__mptr - offsetof(type,member) );})  

    (3)、示例代碼

    Linux內核紅黑樹的使用方法請參考linux-2.6.38.8/Documentation/rbtree.txt文件。 

  1. /* test.c */  
  2. #include <stdio.h>  
  3. #include <stdlib.h>  
  4. #include "rbtree.h"  
  5.   
  6. struct mytype {  
  7.     struct rb_node my_node;  
  8.     int num;  
  9. };  
  10.   
  11. struct mytype *my_search(struct rb_root *root, int num)  
  12. {  
  13.     struct rb_node *node = root->rb_node;  
  14.   
  15.     while (node) {  
  16.     struct mytype *data = container_of(node, struct mytype, my_node);  
  17.   
  18.     if (num < data->num)  
  19.         node = node->rb_left;  
  20.     else if (num > data->num)  
  21.         node = node->rb_right;  
  22.     else  
  23.         return data;  
  24.     }  
  25.       
  26.     return NULL;  
  27. }  
  28.   
  29. int my_insert(struct rb_root *root, struct mytype *data)  
  30. {  
  31.     struct rb_node **tmp = &(root->rb_node), *parent = NULL;  
  32.   
  33.     /* Figure out where to put new node */  
  34.     while (*tmp) {  
  35.     struct mytype *this = container_of(*tmp, struct mytype, my_node);  
  36.   
  37.     parent = *tmp;  
  38.     if (data->num < this->num)  
  39.         tmp = &((*tmp)->rb_left);  
  40.     else if (data->num > this->num)  
  41.         tmp = &((*tmp)->rb_right);  
  42.     else   
  43.         return -1;  
  44.     }  
  45.       
  46.     /* Add new node and rebalance tree. */  
  47.     rb_link_node(&data->my_node, parent, tmp);  
  48.     rb_insert_color(&data->my_node, root);  
  49.       
  50.     return 0;  
  51. }  
  52.   
  53. void my_delete(struct rb_root *root, int num)  
  54. {  
  55.     struct mytype *data = my_search(root, num);  
  56.     if (!data) {   
  57.     fprintf(stderr, "Not found %d.\n", num);  
  58.     return;  
  59.     }  
  60.       
  61.     rb_erase(&data->my_node, root);  
  62.     free(data);  
  63. }  
  64.   
  65. void print_rbtree(struct rb_root *tree)  
  66. {  
  67.     struct rb_node *node;  
  68.       
  69.     for (node = rb_first(tree); node; node = rb_next(node))  
  70.     printf("%d ", rb_entry(node, struct mytype, my_node)->num);  
  71.       
  72.     printf("\n");  
  73. }  
  74.   
  75. int main(int argc, char *argv[])  
  76. {  
  77.     struct rb_root mytree = RB_ROOT;  
  78.     int i, ret, num;  
  79.     struct mytype *tmp;  
  80.   
  81.     if (argc < 2) {  
  82.     fprintf(stderr, "Usage: %s num\n", argv[0]);  
  83.     exit(-1);  
  84.     }  
  85.   
  86.     num = atoi(argv[1]);  
  87.   
  88.     printf("Please enter %d integers:\n", num);  
  89.     for (i = 0; i < num; i++) {  
  90.     tmp = malloc(sizeof(struct mytype));  
  91.     if (!tmp)  
  92.         perror("Allocate dynamic memory");  
  93.   
  94.     scanf("%d", &tmp->num);  
  95.       
  96.     ret = my_insert(&mytree, tmp);  
  97.     if (ret < 0) {  
  98.         fprintf(stderr, "The %d already exists.\n", tmp->num);  
  99.         free(tmp);  
  100.     }  
  101.     }  
  102.   
  103.     printf("\nthe first test\n");  
  104.     print_rbtree(&mytree);  
  105.   
  106.     my_delete(&mytree, 21);  
  107.   
  108.     printf("\nthe second test\n");  
  109.     print_rbtree(&mytree);  
  110.   
  111.     return 0;  
  112. }  

    編譯並執行: 

  1. $ gcc rbtree.c test.c -o test  
  2. richard@tanglinux:~/algorithm/redblack$ ./test 10  
  3. Please enter 10 integers:  
  4. 23  
  5. 4  
  6. 56  
  7. 32  
  8. 89  
  9. 122  
  10. 12  
  11. 21  
  12. 45  
  13. 23  
  14. The 23 already exists.  
  15.   
  16. the first test  
  17. 4 12 21 23 32 45 56 89 122   
  18.   
  19. the second test  
  20. 4 12 23 32 45 56 89 122   

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章