经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » Linux/Shell » 查看文章
Linux内核数据管理利器--红黑树
来源:cnblogs  作者:chegxy  时间:2024/4/1 10:28:29  对本文有异议


写在前面

本文通过两个方面让读者可以深入理解Linux内核中红黑树RB Tree的实现以及使用,读完此文章,你可以收获:

  • 红黑树的特性
  • 红黑树的插入、删除、查询操作
  • 在Linux内核代码中如何使用RB Tree库函数,这一部分通过一个实验带读者体会

1. 红黑树的原理

红黑树RB Tree是二叉树的一种,作为一种自平衡二叉树(一些情况下不是完全平衡的),它在最坏的情况下查询复杂度为\(O(logN)\)。与AVL树类似,尽管RB Tree查询效率不如AVL树(因为RB Tree左右子树高度差距最多接近两倍,而AVL树始终保持左右子树高度最多不超过1),但其插入删除效率高,适合用于大数据量且更新频繁的场景,例如内核IO调度算法。
红黑树在二叉树的基础上做了如下约束:

  1. 树种全部节点要么是黑色要么是红色
  2. 树的根节点是黑色的
  3. 叶节点(指NULL节点)颜色为黑色
  4. 红色节点之间不能相邻
  5. 一个节点的左子树和右子树高度(只统计黑色节点)相同

在介绍红黑树的操作前,我们先说明以下几点惯例:

  • 所有节点在插入的时候都将是红色节点(不包括根节点,其插入时是黑色的),这样有一个好处是可以不违反约束1,2,3和5,对于约束1,2和3是显然的,对于5,由于添加红色节点并不会影响其父节点及以上节点左右子树黑色节点数量,故不违反约束5。因此,在插入节点后,只需判断是否违反约束4。
  • 一颗红黑树中,某一节点左右子树节点高度差不会超过2倍,考虑一种极限情况:左子树黑色节点高度为x,且最长路径中不存在红色节点,这是允许的,右子树有黑色节点高度为x,这样满足约束5,除此之外,右子树最长路径黑色几点之间都由红色节点隔开(满足约束4),故右子树总高度为2x-1,约等于2x。

2. 红黑树操作

在Linux内核代码中仅提供了红黑树节点链接、索引、调整、删除等基础操作,不包含特定含义的查询、插入等操作:

  • void rb_insert_color(struct rb_node *, struct rb_root *);,检查调整一个指定节点,通常与rb_link_node搭配使用;
  • void rb_erase(struct rb_node *, struct rb_root *);,从树中删除一个指定节点;
  • struct rb_node *rb_next(struct rb_node *);,返回一个节点的下一个节点(顺序的);
  • struct rb_node *rb_prev(struct rb_node *);,返回一个节点的上一个节点(顺序的);
  • struct rb_node *rb_first(struct rb_root *);,返回树中的第一个节点(顺序的);
  • struct rb_node *rb_last(struct rb_root *);,返回树中的最后一个节点(顺序的);
  • void rb_replace_node(struct rb_node *victim, struct rb_node *new, struct rb_root *root);,用new替换节点victim
  • inline void rb_link_node(struct rb_node * node, struct rb_node * parent, struct rb_node ** rb_link),将一个节点链接到树中指定位置,parent是父节点,rb_link指定了链接父节点的位置是左还是右。

2.1 红黑树的节点插入

根据第一个部分我们所讲的内容可知,一个节点插入RB Tree时会被染成红色,因此只需要检查插入时是否违反规则4,既插入节点与其父节点是否都是红色,然后做出相应的调整,这些工作由rb_insert_color函数完成,其主要分以下三种情况,第一种是父节点为黑色,那么不需要做任何事情,插入红节点后该树仍然符合所有规则。

  1. void rb_insert_color(struct rb_node *node, struct rb_root *root)
  2. {
  3. struct rb_node *parent, *gparent;
  4. while ((parent = node->rb_parent) && parent->rb_color == RB_RED)
  5. {
  6. ... // 检查与处理
  7. }
  8. root->rb_node->rb_color = RB_BLACK; // 保证根节点是黑色的
  9. }

由代码可知,只要父节点为黑色那么可以直接退出。第二种情况是父节点为红色,此时违反规则4,但是其叔父节点(父节点的父节点的另一个子节点)也是红色,如下图所示,左边四个树包含了全部这种情况,A是祖父,B是插入节点的父节点,E是插入节点。

这种情况下,可以直接将父节点和叔父节点染成黑色,祖父节点染成红色,这样插入节点的父节点解决了规则4,同时祖父节点左右子树黑色节点高度仍然相同,例如上图中的第5棵树,之后将祖父节点作为插入节点继续向上检查,下面的代码执行的正是这一步骤:

  1. void rb_insert_color(struct rb_node *node, struct rb_root *root)
  2. {
  3. struct rb_node *parent, *gparent;
  4. while ((parent = node->rb_parent) && parent->rb_color == RB_RED)
  5. {
  6. gparent = parent->rb_parent; // 祖父节点
  7. if (parent == gparent->rb_left)
  8. {
  9. {
  10. register struct rb_node *uncle = gparent->rb_right;
  11. if (uncle && uncle->rb_color == RB_RED)
  12. {
  13. uncle->rb_color = RB_BLACK;
  14. parent->rb_color = RB_BLACK;
  15. gparent->rb_color = RB_RED;
  16. node = gparent;
  17. continue;
  18. }
  19. }
  20. ... // 其他检查和处理
  21. } else {
  22. {
  23. register struct rb_node *uncle = gparent->rb_left;
  24. if (uncle && uncle->rb_color == RB_RED)
  25. {
  26. uncle->rb_color = RB_BLACK;
  27. parent->rb_color = RB_BLACK;
  28. gparent->rb_color = RB_RED;
  29. node = gparent;
  30. continue;
  31. }
  32. }
  33. ... // 其他检查和处理
  34. }
  35. }
  36. root->rb_node->rb_color = RB_BLACK;
  37. }

第三种情况最为复杂,由于叔父节点不再是红色,故不能只靠染色来解决,其可分为以下四种:

  1. 插入节点为父节点的右节点,父节点为祖父节点的左节点;
  2. 插入节点为父节点的左节点,父节点为祖父节点的左节点;
  3. 插入节点为父节点的右节点,父节点为祖父节点的右节点;
  4. 插入节点为父节点的左节点,父节点为祖父节点的右节点;

在这四种中,第2种(左左)和第3种(右右)需要先进行一次染色解决规则4冲突,然后经过旋转解决染色后的规则5冲突。以左左为例,先将父节点染成黑色,祖父节点染成红色,此时不再有颜色冲突,但是规则5出现冲突,因为左子树显然多出一个黑色节点,所以接下来祖父节点右旋,将父节点作为祖父节点,这样就完成了两个恰到好处的事情:1)祖父节点位置的颜色再次变为黑色,这必然使得祖父不会破坏规则4;2)由于原祖父节点染成红色,所以即使其变成了右子树的节点也不影响规则5。下图展示了这一过程:

对于右右,其与左左区别在于使用左旋,原理可以参考左左自行推断。
对于第1种(右左)和第4种(左右),需要多增加一个旋转,使其变为左左或者右右,然后便可按照左左/右右的规则调整RB Tree,下图展示了右左的调整过程。

需要注意的是,不论是这四种中的哪种,最后操作的结果实际上都是在祖父节点和叔父节点直接新插入了红色节点,祖父节点颜色并没有改变,而且黑色节点数量也没有改变,所以在调整结束后无需继续向上检查。下面是内核中关于第三种情况的处理:

  1. static void __rb_rotate_left(struct rb_node *node, struct rb_root *root)
  2. {
  3. struct rb_node *right = node->rb_right;
  4. if ((node->rb_right = right->rb_left))
  5. right->rb_left->rb_parent = node;
  6. right->rb_left = node;
  7. if ((right->rb_parent = node->rb_parent))
  8. {
  9. if (node == node->rb_parent->rb_left)
  10. node->rb_parent->rb_left = right;
  11. else
  12. node->rb_parent->rb_right = right;
  13. }
  14. else
  15. root->rb_node = right;
  16. node->rb_parent = right;
  17. }
  18. static void __rb_rotate_right(struct rb_node *node, struct rb_root *root)
  19. {
  20. struct rb_node *left = node->rb_left;
  21. if ((node->rb_left = left->rb_right))
  22. left->rb_right->rb_parent = node;
  23. left->rb_right = node;
  24. if ((left->rb_parent = node->rb_parent))
  25. {
  26. if (node == node->rb_parent->rb_right)
  27. node->rb_parent->rb_right = left;
  28. else
  29. node->rb_parent->rb_left = left;
  30. }
  31. else
  32. root->rb_node = left;
  33. node->rb_parent = left;
  34. }
  35. void rb_insert_color(struct rb_node *node, struct rb_root *root)
  36. {
  37. struct rb_node *parent, *gparent;
  38. while ((parent = node->rb_parent) && parent->rb_color == RB_RED)
  39. {
  40. gparent = parent->rb_parent;
  41. if (parent == gparent->rb_left)
  42. {
  43. {
  44. register struct rb_node *uncle = gparent->rb_right;
  45. ... // 叔父为红色的处理
  46. }
  47. if (parent->rb_right == node)
  48. {
  49. register struct rb_node *tmp;
  50. __rb_rotate_left(parent, root);
  51. tmp = parent;
  52. parent = node;
  53. node = tmp;
  54. }
  55. parent->rb_color = RB_BLACK;
  56. gparent->rb_color = RB_RED;
  57. __rb_rotate_right(gparent, root);
  58. } else {
  59. {
  60. register struct rb_node *uncle = gparent->rb_left;
  61. ... // 叔父为红色的处理
  62. }
  63. if (parent->rb_left == node)
  64. {
  65. register struct rb_node *tmp;
  66. __rb_rotate_right(parent, root);
  67. tmp = parent;
  68. parent = node;
  69. node = tmp;
  70. }
  71. parent->rb_color = RB_BLACK;
  72. gparent->rb_color = RB_RED;
  73. __rb_rotate_left(gparent, root);
  74. }
  75. }
  76. root->rb_node->rb_color = RB_BLACK;
  77. }

在Linux内核中,如果需要插入一个节点到RB Tree中,需要执行以下几步:

  1. 遍历RB Tree,找到新节点插入位置;
  2. 调用rb_link_node将节点链接到1找到的位置;
  3. 调用rb_insert_color调整RB Tree,使其符合规则。

2.2 红黑树的节点删除

红黑树的删除比插入操作更为复杂,其分为两个阶段,第一个阶段先删除节点,其技巧为:如果删除节点只有一个孩子或者没孩子,那么直接删除该节点,并链接父节点和孩子节点,代码如下:

  1. void rb_erase(struct rb_node *node, struct rb_root *root)
  2. {
  3. struct rb_node *child, *parent;
  4. int color;
  5. if (!node->rb_left)
  6. child = node->rb_right;
  7. else if (!node->rb_right)
  8. child = node->rb_left;
  9. else
  10. {
  11. ... // 有两个孩子的操作
  12. }
  13. parent = node->rb_parent;
  14. color = node->rb_color;
  15. // 链接父节点和孩子节点
  16. if (child)
  17. child->rb_parent = parent;
  18. if (parent)
  19. {
  20. if (parent->rb_left == node)
  21. parent->rb_left = child;
  22. else
  23. parent->rb_right = child;
  24. }
  25. else
  26. root->rb_node = child;
  27. color: // 第二阶段:调整
  28. if (color == RB_BLACK)
  29. __rb_erase_color(child, parent, root);
  30. }

如果有两个孩子,那么选择删除节点的顺序下一个节点替换删除节点,既删除位置变到了删除节点的顺序下一个节点的原先位置,这样可以保证删除节点只有一个右子树(因为删除节点的顺序下一个节点是删除节点的右子树的最左边的叶子节点),代码如下:

  1. void rb_erase(struct rb_node *node, struct rb_root *root)
  2. {
  3. struct rb_node *child, *parent;
  4. int color;
  5. if (!node->rb_left)
  6. ...
  7. else if (!node->rb_right)
  8. ...
  9. else
  10. {
  11. struct rb_node *old = node, *left;
  12. node = node->rb_right;
  13. while ((left = node->rb_left) != NULL)
  14. node = left;
  15. // 此时 node 为 删除节点的顺序下一个节点(只有右子树或者无孩子),old 为原删除节点
  16. child = node->rb_right;
  17. parent = node->rb_parent;
  18. color = node->rb_color;
  19. // 链接删除节点的顺序下一个节点的孩子节点和父节点
  20. if (child)
  21. child->rb_parent = parent;
  22. if (parent)
  23. {
  24. if (parent->rb_left == node)
  25. parent->rb_left = child;
  26. else
  27. parent->rb_right = child;
  28. }
  29. else
  30. root->rb_node = child;
  31. if (node->rb_parent == old) // 由于 old 是待删除节点,而 parent 此时指向 old,所以要将 parent 指向新的 node
  32. parent = node;
  33. // node 节点替换原删除节点
  34. node->rb_parent = old->rb_parent;
  35. node->rb_color = old->rb_color;
  36. node->rb_right = old->rb_right;
  37. node->rb_left = old->rb_left;
  38. // 将新 node 链接到原删除节点 old 的父节点上
  39. if (old->rb_parent)
  40. {
  41. if (old->rb_parent->rb_left == old)
  42. old->rb_parent->rb_left = node;
  43. else
  44. old->rb_parent->rb_right = node;
  45. } else
  46. root->rb_node = node;
  47. // 将新 node 链接到原删除节点 old 的子节点上
  48. old->rb_left->rb_parent = node;
  49. if (old->rb_right) // 可能删除的右子树只有一个节点,删除后变为NULL
  50. old->rb_right->rb_parent = node;
  51. goto color;
  52. }
  53. color: // 第二阶段:调整
  54. if (color == RB_BLACK)
  55. __rb_erase_color(child, parent, root);
  56. }

第二阶段

当在第一阶段确定了删除节点位置(通常其只有一个子树或者没有子树)后,将会检查是否要进行调色和旋转使得节点删除后的RB Tree再次符合规则。我们在下面通过5种大的情况来讲解这一操作。
(1) 最简单的情况是:我们删除的节点颜色是红色的,这意味着节点删除后,子树连接到其父节点后黑色节点高度不变,因此无需调整,这点可以在rb_erase函数的最后印证,因为只有删除节点为黑色才需要执行__rb_erase_color函数。

(2) 稍微复杂的一种情况是:我们删除的节点B颜色是黑色,同时其父节点的另一个孩子节点C颜色也是黑色且其左右孩子节点E/F也为黑色。由于父节点A的一边少了一个黑色节点,所以应该把另一边的黑色节点染成红色,这样父节点A的左右黑色节点高度相同,而且C和E/F节点颜色不冲突。对于父节点A,如果其为红色,那正好,将其染色为黑色,这样以A为根的子树高度又恢复原样,且颜色也不会冲突;如果A为黑色,那么就要继续向上检查调整,代码如下:

  1. static void __rb_erase_color(struct rb_node *node, struct rb_node *parent,
  2. struct rb_root *root)
  3. {
  4. struct rb_node *other;
  5. while ((!node || node->rb_color == RB_BLACK) && node != root->rb_node)
  6. {
  7. if (parent->rb_left == node)
  8. {
  9. other = parent->rb_right;
  10. if (other->rb_color == RB_RED)
  11. {
  12. ...
  13. }
  14. if ((!other->rb_left ||
  15. other->rb_left->rb_color == RB_BLACK)
  16. && (!other->rb_right ||
  17. other->rb_right->rb_color == RB_BLACK))
  18. {
  19. other->rb_color = RB_RED;
  20. node = parent;
  21. parent = node->rb_parent;
  22. }
  23. else
  24. {
  25. ...
  26. }
  27. }
  28. else
  29. {
  30. other = parent->rb_left;
  31. if (other->rb_color == RB_RED)
  32. {
  33. ...
  34. }
  35. if ((!other->rb_left ||
  36. other->rb_left->rb_color == RB_BLACK)
  37. && (!other->rb_right ||
  38. other->rb_right->rb_color == RB_BLACK))
  39. {
  40. other->rb_color = RB_RED;
  41. node = parent;
  42. parent = node->rb_parent;
  43. }
  44. else
  45. {
  46. ...
  47. }
  48. }
  49. }
  50. if (node)
  51. node->rb_color = RB_BLACK;
  52. }

下面以删除节点为左子树为例展示了调色过程:

(3) 我们删除的节点B颜色是黑色的,同时其父节点A的另一个孩子节点C颜色是黑色的,而C左孩子节点E为黑色,右孩子节点F为红色。对于这种情况,可以将父节点染色成黑色左旋/右旋使得删除节点一侧增加一个黑色节点,对于另一边,因为C因为旋转变成了子树根节点,所以其应该继承原先子树根节点颜色。除此之外,由于C不再是子树节点,所以少了一个黑色节点,所以要把F染成黑色,代码如下:

  1. static void __rb_erase_color(struct rb_node *node, struct rb_node *parent,
  2. struct rb_root *root)
  3. {
  4. struct rb_node *other;
  5. while ((!node || node->rb_color == RB_BLACK) && node != root->rb_node)
  6. {
  7. if (parent->rb_left == node)
  8. {
  9. other = parent->rb_right;
  10. if (other->rb_color == RB_RED)
  11. {
  12. ...
  13. }
  14. if ((!other->rb_left ||
  15. other->rb_left->rb_color == RB_BLACK)
  16. && (!other->rb_right ||
  17. other->rb_right->rb_color == RB_BLACK))
  18. {
  19. ...
  20. }
  21. else
  22. {
  23. if (!other->rb_right ||
  24. other->rb_right->rb_color == RB_BLACK)
  25. {
  26. ...
  27. }
  28. other->rb_color = parent->rb_color;
  29. parent->rb_color = RB_BLACK;
  30. if (other->rb_right)
  31. other->rb_right->rb_color = RB_BLACK;
  32. __rb_rotate_left(parent, root);
  33. node = root->rb_node;
  34. break;
  35. }
  36. }
  37. else
  38. {
  39. other = parent->rb_left;
  40. if (other->rb_color == RB_RED)
  41. {
  42. ...
  43. }
  44. if ((!other->rb_left ||
  45. other->rb_left->rb_color == RB_BLACK)
  46. && (!other->rb_right ||
  47. other->rb_right->rb_color == RB_BLACK))
  48. {
  49. ...
  50. }
  51. else
  52. {
  53. if (!other->rb_left ||
  54. other->rb_left->rb_color == RB_BLACK)
  55. {
  56. ...
  57. }
  58. other->rb_color = parent->rb_color;
  59. parent->rb_color = RB_BLACK;
  60. if (other->rb_left)
  61. other->rb_left->rb_color = RB_BLACK;
  62. __rb_rotate_right(parent, root);
  63. node = root->rb_node;
  64. break;
  65. }
  66. }
  67. }
  68. if (node)
  69. node->rb_color = RB_BLACK;
  70. }

下面以删除节点为左子树为例展示了调色过程:

(4) 我们删除的节点B颜色是黑色的,同时其父节点A的另一个孩子节点C颜色是黑色的,而C左孩子节点E为红色,右孩子节点F为黑色。对于这种情况,应该先经过染色和旋转将其变为情况(3)。其过程为将C染成红色右旋,这样C原先这颗子树左右子树黑色节点高度不变,只是C和E颜色冲突,不过这不用担心,按照(3)的方法,C最后变成黑色,而E变成了原先A的颜色,代码如下:

  1. struct rb_root *root)
  2. {
  3. struct rb_node *other;
  4. while ((!node || node->rb_color == RB_BLACK) && node != root->rb_node)
  5. {
  6. if (parent->rb_left == node)
  7. {
  8. other = parent->rb_right;
  9. if (other->rb_color == RB_RED)
  10. {
  11. ...
  12. }
  13. if ((!other->rb_left ||
  14. other->rb_left->rb_color == RB_BLACK)
  15. && (!other->rb_right ||
  16. other->rb_right->rb_color == RB_BLACK))
  17. {
  18. ...
  19. }
  20. else
  21. {
  22. if (!other->rb_right ||
  23. other->rb_right->rb_color == RB_BLACK)
  24. {
  25. register struct rb_node *o_left;
  26. if ((o_left = other->rb_left))
  27. o_left->rb_color = RB_BLACK;
  28. other->rb_color = RB_RED;
  29. __rb_rotate_right(other, root);
  30. other = parent->rb_right;
  31. }
  32. other->rb_color = parent->rb_color;
  33. parent->rb_color = RB_BLACK;
  34. if (other->rb_right)
  35. other->rb_right->rb_color = RB_BLACK;
  36. __rb_rotate_left(parent, root);
  37. node = root->rb_node;
  38. break;
  39. }
  40. }
  41. else
  42. {
  43. other = parent->rb_left;
  44. if (other->rb_color == RB_RED)
  45. {
  46. ...
  47. }
  48. if ((!other->rb_left ||
  49. other->rb_left->rb_color == RB_BLACK)
  50. && (!other->rb_right ||
  51. other->rb_right->rb_color == RB_BLACK))
  52. {
  53. ...
  54. }
  55. else
  56. {
  57. if (!other->rb_left ||
  58. other->rb_left->rb_color == RB_BLACK)
  59. {
  60. register struct rb_node *o_right;
  61. if ((o_right = other->rb_right))
  62. o_right->rb_color = RB_BLACK;
  63. other->rb_color = RB_RED;
  64. __rb_rotate_left(other, root);
  65. other = parent->rb_left;
  66. }
  67. other->rb_color = parent->rb_color;
  68. parent->rb_color = RB_BLACK;
  69. if (other->rb_left)
  70. other->rb_left->rb_color = RB_BLACK;
  71. __rb_rotate_right(parent, root);
  72. node = root->rb_node;
  73. break;
  74. }
  75. }
  76. }
  77. if (node)
  78. node->rb_color = RB_BLACK;
  79. }

下面以删除节点为左子树为例展示了调色过程:

(5) 我们删除的节点B颜色是黑色的,同时其父节点A的另一个孩子节点C颜色是红色的。对于这种情况,意味着父节点A必定为黑色的,而C的E/F孩子节点为黑色的,因此我们可以通过将A染成红色左旋/右旋,然后C染成黑色,这样,这颗子树黑色节点高度不变,同时删除节点一侧的子树变成了(3)或者(4)的情况,因为经过旋转,A的右节点变成了黑色,代码如下:

  1. struct rb_root *root)
  2. {
  3. struct rb_node *other;
  4. while ((!node || node->rb_color == RB_BLACK) && node != root->rb_node)
  5. {
  6. if (parent->rb_left == node)
  7. {
  8. other = parent->rb_right;
  9. if (other->rb_color == RB_RED)
  10. {
  11. other->rb_color = RB_BLACK;
  12. parent->rb_color = RB_RED;
  13. __rb_rotate_left(parent, root);
  14. other = parent->rb_right;
  15. }
  16. ...
  17. }
  18. else
  19. {
  20. other = parent->rb_left;
  21. if (other->rb_color == RB_RED)
  22. {
  23. other->rb_color = RB_BLACK;
  24. parent->rb_color = RB_RED;
  25. __rb_rotate_right(parent, root);
  26. other = parent->rb_left;
  27. }
  28. ...
  29. }
  30. }
  31. if (node)
  32. node->rb_color = RB_BLACK;
  33. }

下面以删除节点为左子树为例展示了调色过程:

2.3 红黑树的查询操作

Linux内核中红黑树库提供的功能没有特定某一种排序方法,所以也没有给出查询接口。由于红黑树也是二叉排序树的一种,以升序为例,我们只需要按照以下流程即可进行查询操作:

  1. Query x:
  2. node = root
  3. while node is not null and node.value != x:
  4. if node.value < x
  5. node = node.right
  6. else:
  7. node = node.left
  8. Return node

3. 红黑树操作实验

实验介绍:有一种对象Item,里面包含:1)树节点,用于管理RB Tree;2)数值,表示了对象的实际内容;3)出现次数,由于我们希望节点随机产生,因此可能存在重复的情况,该值用于统计相同节点的数量。我们先随机num个Item,然后使用这些Item构建出红黑树。最后通过输入要擦除的对象,我们将其从树中删除并显示。

下图时代码运行后的效果,每个节点打印含义为[数值,出现次数,节点颜色],最左边为根节点,左节点在右节点上方。

附录A: 实验代码

  1. main.c :
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5. #include "rbtree.h"
  6. typedef struct _Item
  7. {
  8. int val;
  9. int num; // appear num
  10. struct rb_node node;
  11. }Item;
  12. static int print_num = 0;
  13. static int print_level = 0;
  14. Item* GenerateItem();
  15. void DFS(struct rb_node *node);
  16. int main()
  17. {
  18. int num = 0;
  19. Item *item, *cur, *prev = NULL;
  20. struct rb_node **link;
  21. struct rb_root root = RB_ROOT;
  22. srand(time(NULL));
  23. printf("Test item num: ");
  24. scanf("%d", &num);
  25. print_num = 0;
  26. printf("Generate Item[%d]:\n", num);
  27. /* generate a random rb tree with [num] node */
  28. while (num > 0)
  29. {
  30. /* randomize a rb tree node */
  31. item = GenerateItem();
  32. if (print_num == 16)
  33. {
  34. printf("\n");
  35. print_num = 0;
  36. }
  37. printf("%d\t", item->val);
  38. /* insert a rb tree node to rb tree */
  39. if (!root.rb_node) // empty rb tree
  40. {
  41. root.rb_node = &(item->node);
  42. rb_insert_color(&(item->node), &root);
  43. goto next_loop;
  44. }
  45. cur = rb_entry(root.rb_node, Item, node);
  46. /* 1. find insert position */
  47. while (cur)
  48. {
  49. if (cur->val == item->val) // the same item
  50. {
  51. cur->num++;
  52. free(item);
  53. goto next_loop;
  54. }
  55. else if (cur->val > item->val)
  56. {
  57. prev = cur;
  58. link = &(cur->node.rb_left);
  59. if (cur->node.rb_left == NULL)
  60. {
  61. break;
  62. }
  63. cur = rb_entry(cur->node.rb_left, Item, node);
  64. }
  65. else
  66. {
  67. prev = cur;
  68. link = &(cur->node.rb_right);
  69. if (cur->node.rb_right == NULL)
  70. {
  71. break;
  72. }
  73. cur = rb_entry(cur->node.rb_right, Item, node);
  74. }
  75. }
  76. /* 2. link node */
  77. rb_link_node(&(item->node), &(prev->node), link);
  78. /* 3. adjust */
  79. rb_insert_color(&(item->node), &root);
  80. next_loop:
  81. num--;
  82. }
  83. /* print a generated rb tree */
  84. print_num = 0;
  85. print_level = 0;
  86. printf("\nsort result:\n");
  87. DFS(root.rb_node);
  88. printf("\n");
  89. /* testing erase some rb tree node */
  90. printf("\nTest Erase, input node value to erase its node, or input negative value to exit\n");
  91. while (1)
  92. {
  93. /* get the node need to erase */
  94. printf(">>");
  95. scanf("%d", &num);
  96. if (num < 0)
  97. {
  98. break;
  99. }
  100. /* 1. find insert position */
  101. if (!root.rb_node) // empty rb tree
  102. {
  103. printf("empty tree\n");
  104. break;
  105. }
  106. cur = rb_entry(root.rb_node, Item, node);
  107. while (cur)
  108. {
  109. if (cur->val == num) // the same item
  110. {
  111. break;
  112. }
  113. else if (cur->val > num)
  114. {
  115. if (cur->node.rb_left == NULL)
  116. {
  117. cur = NULL;
  118. break;
  119. }
  120. cur = rb_entry(cur->node.rb_left, Item, node);
  121. }
  122. else
  123. {
  124. if (cur->node.rb_right == NULL)
  125. {
  126. cur = NULL;
  127. break;
  128. }
  129. cur = rb_entry(cur->node.rb_right, Item, node);
  130. }
  131. }
  132. /* 2. do erase function */
  133. if (cur)
  134. {
  135. printf("erase %d\n", num);
  136. rb_erase(&(cur->node), &root);
  137. free(cur);
  138. DFS(root.rb_node);
  139. printf("\n");
  140. }
  141. else
  142. {
  143. printf("not exist\n");
  144. }
  145. printf("===================================================================\n");
  146. }
  147. return 0;
  148. }
  149. Item* GenerateItem()
  150. {
  151. Item *item = (Item*)malloc(sizeof(Item));
  152. item->val = rand() % 1000;
  153. item->num = 1;
  154. item->node.rb_parent = NULL;
  155. item->node.rb_left = NULL;
  156. item->node.rb_right = NULL;
  157. return item;
  158. }
  159. void DFS(struct rb_node *node)
  160. {
  161. Item *item;
  162. int i;
  163. if (node)
  164. {
  165. print_level++;
  166. DFS(node->rb_left);
  167. if (print_num == 4)
  168. {
  169. printf("\n");
  170. print_num = 0;
  171. }
  172. item = rb_entry(node, Item, node);
  173. for (i = 1; i < print_level; i++)
  174. {
  175. printf(" ");
  176. }
  177. printf("[%3d,%3d,%c]\n", item->val, item->num, (item->node.rb_color == RB_RED) ? 'R' : 'B');
  178. print_num++;
  179. DFS(node->rb_right);
  180. print_level--;
  181. }
  182. }
  183. rbtree.h :
  184. /*
  185. Red Black Trees
  186. (C) 1999 Andrea Arcangeli <andrea@suse.de>
  187. This program is free software; you can redistribute it and/or modify
  188. it under the terms of the GNU General Public License as published by
  189. the Free Software Foundation; either version 2 of the License, or
  190. (at your option) any later version.
  191. This program is distributed in the hope that it will be useful,
  192. but WITHOUT ANY WARRANTY; without even the implied warranty of
  193. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  194. GNU General Public License for more details.
  195. You should have received a copy of the GNU General Public License
  196. along with this program; if not, write to the Free Software
  197. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  198. linux/include/linux/rbtree.h
  199. To use rbtrees you'll have to implement your own insert and search cores.
  200. This will avoid us to use callbacks and to drop drammatically performances.
  201. I know it's not the cleaner way, but in C (not in C++) to get
  202. performances and genericity...
  203. Some example of insert and search follows here. The search is a plain
  204. normal search over an ordered tree. The insert instead must be implemented
  205. int two steps: as first thing the code must insert the element in
  206. order as a red leaf in the tree, then the support library function
  207. rb_insert_color() must be called. Such function will do the
  208. not trivial work to rebalance the rbtree if necessary.
  209. -----------------------------------------------------------------------
  210. static inline struct page * rb_search_page_cache(struct inode * inode,
  211. unsigned long offset)
  212. {
  213. struct rb_node * n = inode->i_rb_page_cache.rb_node;
  214. struct page * page;
  215. while (n)
  216. {
  217. page = rb_entry(n, struct page, rb_page_cache);
  218. if (offset < page->offset)
  219. n = n->rb_left;
  220. else if (offset > page->offset)
  221. n = n->rb_right;
  222. else
  223. return page;
  224. }
  225. return NULL;
  226. }
  227. static inline struct page * __rb_insert_page_cache(struct inode * inode,
  228. unsigned long offset,
  229. struct rb_node * node)
  230. {
  231. struct rb_node ** p = &inode->i_rb_page_cache.rb_node;
  232. struct rb_node * parent = NULL;
  233. struct page * page;
  234. while (*p)
  235. {
  236. parent = *p;
  237. page = rb_entry(parent, struct page, rb_page_cache);
  238. if (offset < page->offset)
  239. p = &(*p)->rb_left;
  240. else if (offset > page->offset)
  241. p = &(*p)->rb_right;
  242. else
  243. return page;
  244. }
  245. rb_link_node(node, parent, p);
  246. return NULL;
  247. }
  248. static inline struct page * rb_insert_page_cache(struct inode * inode,
  249. unsigned long offset,
  250. struct rb_node * node)
  251. {
  252. struct page * ret;
  253. if ((ret = __rb_insert_page_cache(inode, offset, node)))
  254. goto out;
  255. rb_insert_color(node, &inode->i_rb_page_cache);
  256. out:
  257. return ret;
  258. }
  259. -----------------------------------------------------------------------
  260. */
  261. #ifndef _LINUX_RBTREE_H
  262. #define _LINUX_RBTREE_H
  263. // #include <linux/kernel.h>
  264. // #include <linux/stddef.h>
  265. #include <stdlib.h>
  266. #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE*)0)->MEMBER)
  267. #define container_of(ptr, type, member) ({ const typeof( ((type *)0)->member ) *__mptr = (ptr); (type *)( (char *)__mptr - offsetof(type,member) );})
  268. struct rb_node
  269. {
  270. struct rb_node *rb_parent;
  271. int rb_color;
  272. #define RB_RED 0
  273. #define RB_BLACK 1
  274. struct rb_node *rb_right;
  275. struct rb_node *rb_left;
  276. };
  277. struct rb_root
  278. {
  279. struct rb_node *rb_node;
  280. };
  281. #define RB_ROOT (struct rb_root) { NULL, }
  282. #define rb_entry(ptr, type, member) container_of(ptr, type, member)
  283. extern void rb_insert_color(struct rb_node *, struct rb_root *);
  284. extern void rb_erase(struct rb_node *, struct rb_root *);
  285. /* Find logical next and previous nodes in a tree */
  286. extern struct rb_node *rb_next(struct rb_node *);
  287. extern struct rb_node *rb_prev(struct rb_node *);
  288. extern struct rb_node *rb_first(struct rb_root *);
  289. extern struct rb_node *rb_last(struct rb_root *);
  290. /* Fast replacement of a single node without remove/rebalance/add/rebalance */
  291. extern void rb_replace_node(struct rb_node *victim, struct rb_node *new,
  292. struct rb_root *root);
  293. static inline void rb_link_node(struct rb_node * node, struct rb_node * parent,
  294. struct rb_node ** rb_link)
  295. {
  296. node->rb_parent = parent;
  297. node->rb_color = RB_RED;
  298. node->rb_left = node->rb_right = NULL;
  299. *rb_link = node;
  300. }
  301. #endif /* _LINUX_RBTREE_H */
  302. rbtree.c :
  303. /*
  304. Red Black Trees
  305. (C) 1999 Andrea Arcangeli <andrea@suse.de>
  306. (C) 2002 David Woodhouse <dwmw2@infradead.org>
  307. This program is free software; you can redistribute it and/or modify
  308. it under the terms of the GNU General Public License as published by
  309. the Free Software Foundation; either version 2 of the License, or
  310. (at your option) any later version.
  311. This program is distributed in the hope that it will be useful,
  312. but WITHOUT ANY WARRANTY; without even the implied warranty of
  313. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  314. GNU General Public License for more details.
  315. You should have received a copy of the GNU General Public License
  316. along with this program; if not, write to the Free Software
  317. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  318. linux/lib/rbtree.c
  319. */
  320. // #include <linux/rbtree.h>
  321. // #include <linux/module.h>
  322. #include "rbtree.h"
  323. static void __rb_rotate_left(struct rb_node *node, struct rb_root *root)
  324. {
  325. struct rb_node *right = node->rb_right;
  326. if ((node->rb_right = right->rb_left))
  327. right->rb_left->rb_parent = node;
  328. right->rb_left = node;
  329. if ((right->rb_parent = node->rb_parent))
  330. {
  331. if (node == node->rb_parent->rb_left)
  332. node->rb_parent->rb_left = right;
  333. else
  334. node->rb_parent->rb_right = right;
  335. }
  336. else
  337. root->rb_node = right;
  338. node->rb_parent = right;
  339. }
  340. static void __rb_rotate_right(struct rb_node *node, struct rb_root *root)
  341. {
  342. struct rb_node *left = node->rb_left;
  343. if ((node->rb_left = left->rb_right))
  344. left->rb_right->rb_parent = node;
  345. left->rb_right = node;
  346. if ((left->rb_parent = node->rb_parent))
  347. {
  348. if (node == node->rb_parent->rb_right)
  349. node->rb_parent->rb_right = left;
  350. else
  351. node->rb_parent->rb_left = left;
  352. }
  353. else
  354. root->rb_node = left;
  355. node->rb_parent = left;
  356. }
  357. void rb_insert_color(struct rb_node *node, struct rb_root *root)
  358. {
  359. struct rb_node *parent, *gparent;
  360. while ((parent = node->rb_parent) && parent->rb_color == RB_RED)
  361. {
  362. gparent = parent->rb_parent;
  363. if (parent == gparent->rb_left)
  364. {
  365. {
  366. register struct rb_node *uncle = gparent->rb_right;
  367. if (uncle && uncle->rb_color == RB_RED)
  368. {
  369. uncle->rb_color = RB_BLACK;
  370. parent->rb_color = RB_BLACK;
  371. gparent->rb_color = RB_RED;
  372. node = gparent;
  373. continue;
  374. }
  375. }
  376. if (parent->rb_right == node)
  377. {
  378. register struct rb_node *tmp;
  379. __rb_rotate_left(parent, root);
  380. tmp = parent;
  381. parent = node;
  382. node = tmp;
  383. }
  384. parent->rb_color = RB_BLACK;
  385. gparent->rb_color = RB_RED;
  386. __rb_rotate_right(gparent, root);
  387. } else {
  388. {
  389. register struct rb_node *uncle = gparent->rb_left;
  390. if (uncle && uncle->rb_color == RB_RED)
  391. {
  392. uncle->rb_color = RB_BLACK;
  393. parent->rb_color = RB_BLACK;
  394. gparent->rb_color = RB_RED;
  395. node = gparent;
  396. continue;
  397. }
  398. }
  399. if (parent->rb_left == node)
  400. {
  401. register struct rb_node *tmp;
  402. __rb_rotate_right(parent, root);
  403. tmp = parent;
  404. parent = node;
  405. node = tmp;
  406. }
  407. parent->rb_color = RB_BLACK;
  408. gparent->rb_color = RB_RED;
  409. __rb_rotate_left(gparent, root);
  410. }
  411. }
  412. root->rb_node->rb_color = RB_BLACK;
  413. }
  414. static void __rb_erase_color(struct rb_node *node, struct rb_node *parent,
  415. struct rb_root *root)
  416. {
  417. struct rb_node *other;
  418. while ((!node || node->rb_color == RB_BLACK) && node != root->rb_node)
  419. {
  420. if (parent->rb_left == node)
  421. {
  422. other = parent->rb_right;
  423. if (other->rb_color == RB_RED)
  424. {
  425. other->rb_color = RB_BLACK;
  426. parent->rb_color = RB_RED;
  427. __rb_rotate_left(parent, root);
  428. other = parent->rb_right;
  429. }
  430. if ((!other->rb_left ||
  431. other->rb_left->rb_color == RB_BLACK)
  432. && (!other->rb_right ||
  433. other->rb_right->rb_color == RB_BLACK))
  434. {
  435. other->rb_color = RB_RED;
  436. node = parent;
  437. parent = node->rb_parent;
  438. }
  439. else
  440. {
  441. if (!other->rb_right ||
  442. other->rb_right->rb_color == RB_BLACK)
  443. {
  444. register struct rb_node *o_left;
  445. if ((o_left = other->rb_left))
  446. o_left->rb_color = RB_BLACK;
  447. other->rb_color = RB_RED;
  448. __rb_rotate_right(other, root);
  449. other = parent->rb_right;
  450. }
  451. other->rb_color = parent->rb_color;
  452. parent->rb_color = RB_BLACK;
  453. if (other->rb_right)
  454. other->rb_right->rb_color = RB_BLACK;
  455. __rb_rotate_left(parent, root);
  456. node = root->rb_node;
  457. break;
  458. }
  459. }
  460. else
  461. {
  462. other = parent->rb_left;
  463. if (other->rb_color == RB_RED)
  464. {
  465. other->rb_color = RB_BLACK;
  466. parent->rb_color = RB_RED;
  467. __rb_rotate_right(parent, root);
  468. other = parent->rb_left;
  469. }
  470. if ((!other->rb_left ||
  471. other->rb_left->rb_color == RB_BLACK)
  472. && (!other->rb_right ||
  473. other->rb_right->rb_color == RB_BLACK))
  474. {
  475. other->rb_color = RB_RED;
  476. node = parent;
  477. parent = node->rb_parent;
  478. }
  479. else
  480. {
  481. if (!other->rb_left ||
  482. other->rb_left->rb_color == RB_BLACK)
  483. {
  484. register struct rb_node *o_right;
  485. if ((o_right = other->rb_right))
  486. o_right->rb_color = RB_BLACK;
  487. other->rb_color = RB_RED;
  488. __rb_rotate_left(other, root);
  489. other = parent->rb_left;
  490. }
  491. other->rb_color = parent->rb_color;
  492. parent->rb_color = RB_BLACK;
  493. if (other->rb_left)
  494. other->rb_left->rb_color = RB_BLACK;
  495. __rb_rotate_right(parent, root);
  496. node = root->rb_node;
  497. break;
  498. }
  499. }
  500. }
  501. if (node)
  502. node->rb_color = RB_BLACK;
  503. }
  504. void rb_erase(struct rb_node *node, struct rb_root *root)
  505. {
  506. struct rb_node *child, *parent;
  507. int color;
  508. if (!node->rb_left)
  509. child = node->rb_right;
  510. else if (!node->rb_right)
  511. child = node->rb_left;
  512. else
  513. {
  514. struct rb_node *old = node, *left;
  515. node = node->rb_right;
  516. while ((left = node->rb_left) != NULL)
  517. node = left;
  518. child = node->rb_right;
  519. parent = node->rb_parent;
  520. color = node->rb_color;
  521. if (child)
  522. child->rb_parent = parent;
  523. if (parent)
  524. {
  525. if (parent->rb_left == node)
  526. parent->rb_left = child;
  527. else
  528. parent->rb_right = child;
  529. }
  530. else
  531. root->rb_node = child;
  532. if (node->rb_parent == old)
  533. parent = node;
  534. node->rb_parent = old->rb_parent;
  535. node->rb_color = old->rb_color;
  536. node->rb_right = old->rb_right;
  537. node->rb_left = old->rb_left;
  538. if (old->rb_parent)
  539. {
  540. if (old->rb_parent->rb_left == old)
  541. old->rb_parent->rb_left = node;
  542. else
  543. old->rb_parent->rb_right = node;
  544. } else
  545. root->rb_node = node;
  546. old->rb_left->rb_parent = node;
  547. if (old->rb_right)
  548. old->rb_right->rb_parent = node;
  549. goto color;
  550. }
  551. parent = node->rb_parent;
  552. color = node->rb_color;
  553. if (child)
  554. child->rb_parent = parent;
  555. if (parent)
  556. {
  557. if (parent->rb_left == node)
  558. parent->rb_left = child;
  559. else
  560. parent->rb_right = child;
  561. }
  562. else
  563. root->rb_node = child;
  564. color:
  565. if (color == RB_BLACK)
  566. __rb_erase_color(child, parent, root);
  567. }
  568. /*
  569. * This function returns the first node (in sort order) of the tree.
  570. */
  571. struct rb_node *rb_first(struct rb_root *root)
  572. {
  573. struct rb_node *n;
  574. n = root->rb_node;
  575. if (!n)
  576. return NULL;
  577. while (n->rb_left)
  578. n = n->rb_left;
  579. return n;
  580. }
  581. struct rb_node *rb_last(struct rb_root *root)
  582. {
  583. struct rb_node *n;
  584. n = root->rb_node;
  585. if (!n)
  586. return NULL;
  587. while (n->rb_right)
  588. n = n->rb_right;
  589. return n;
  590. }
  591. struct rb_node *rb_next(struct rb_node *node)
  592. {
  593. /* If we have a right-hand child, go down and then left as far
  594. as we can. */
  595. if (node->rb_right) {
  596. node = node->rb_right;
  597. while (node->rb_left)
  598. node=node->rb_left;
  599. return node;
  600. }
  601. /* No right-hand children. Everything down and left is
  602. smaller than us, so any 'next' node must be in the general
  603. direction of our parent. Go up the tree; any time the
  604. ancestor is a right-hand child of its parent, keep going
  605. up. First time it's a left-hand child of its parent, said
  606. parent is our 'next' node. */
  607. while (node->rb_parent && node == node->rb_parent->rb_right)
  608. node = node->rb_parent;
  609. return node->rb_parent;
  610. }
  611. struct rb_node *rb_prev(struct rb_node *node)
  612. {
  613. /* If we have a left-hand child, go down and then right as far
  614. as we can. */
  615. if (node->rb_left) {
  616. node = node->rb_left;
  617. while (node->rb_right)
  618. node=node->rb_right;
  619. return node;
  620. }
  621. /* No left-hand children. Go up till we find an ancestor which
  622. is a right-hand child of its parent */
  623. while (node->rb_parent && node == node->rb_parent->rb_left)
  624. node = node->rb_parent;
  625. return node->rb_parent;
  626. }
  627. void rb_replace_node(struct rb_node *victim, struct rb_node *new,
  628. struct rb_root *root)
  629. {
  630. struct rb_node *parent = victim->rb_parent;
  631. /* Set the surrounding nodes to point to the replacement */
  632. if (parent) {
  633. if (victim == parent->rb_left)
  634. parent->rb_left = new;
  635. else
  636. parent->rb_right = new;
  637. } else {
  638. root->rb_node = new;
  639. }
  640. if (victim->rb_left)
  641. victim->rb_left->rb_parent = new;
  642. if (victim->rb_right)
  643. victim->rb_right->rb_parent = new;
  644. /* Copy the pointers/colour from the victim to the replacement */
  645. *new = *victim;
  646. }

2024-3-23 created by chegxy
<chegxy's blog website>

原文链接:https://www.cnblogs.com/chegxy/p/18091738

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号