歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 算法導論-紅黑樹C++實現

算法導論-紅黑樹C++實現

日期:2017/3/1 10:07:23   编辑:Linux編程

紅黑樹的定義:

一棵二叉查找樹如果滿足下面的紅黑性質,則為一棵紅黑樹:

1)每個節點或是紅的,或是黑的。
2)根節點是黑的。
3)每個葉節點(NIL)是黑節點。
4)如果一個節點是紅的,則它的兩個兒子都是黑的。
5)對每個節點,從該節點到其子孫節點的所有路徑上包含相同節點數目的黑節點。

C++代碼實現:
BRTreeNode.h

  1. #ifndef BRTREENODE_H_INCLUDED
  2. #define BRTREENODE_H_INCLUDED
  3. #include<iostream>
  4. usingnamespace std;
  5. class BRTree;
  6. class BRTreeNode
  7. {
  8. private:
  9. friendclass BRTree;
  10. int key;
  11. bool color;
  12. BRTreeNode* left;
  13. BRTreeNode* right;
  14. BRTreeNode* parent;
  15. public:
  16. BRTreeNode():key(-1),color(0),left(NULL),right(NULL),parent(NULL){}
  17. BRTreeNode(BRTreeNode* node):key(node->key),color(node->color),left(node->left),right(node->right),parent(node->parent)
  18. {}
  19. BRTreeNode(int num,bool flag):key(num),color(flag),left(NULL),right(NULL),parent(NULL){}
  20. ~BRTreeNode()
  21. {
  22. }
  23. int Getkey()
  24. {
  25. return key;
  26. }
  27. bool Getcolor()
  28. {
  29. returnthis->color;
  30. }
  31. BRTreeNode* GetLeft()
  32. {
  33. returnthis->left;
  34. }
  35. BRTreeNode* Getright()
  36. {
  37. returnthis->right;
  38. }
  39. BRTreeNode* Getparent()
  40. {
  41. returnthis->parent;
  42. }
  43. void Inorder()
  44. {
  45. if(this!=NULL)
  46. {
  47. this->left->Inorder();
  48. cout<<this->key<<" ";
  49. this->right->Inorder();
  50. }
  51. }
  52. void Preorder()
  53. {
  54. if(this!=NULL)
  55. {
  56. cout<<this->key<<" ";
  57. this->left->Preorder();
  58. this->right->Preorder();
  59. }
  60. }
  61. void Postorder()
  62. {
  63. if(this!=NULL)
  64. {
  65. this->left->Postorder();
  66. this->right->Postorder();
  67. cout<<this->key<<" ";
  68. }
  69. }
  70. void MakeEmpty()
  71. {
  72. if(this!=NULL)
  73. {
  74. this->left->MakeEmpty();
  75. this->right->MakeEmpty();
  76. deletethis;
  77. }
  78. }
  79. int GetHeight()
  80. {
  81. int L,R;
  82. if(this==NULL)
  83. {
  84. return 0;
  85. }
  86. L=this->left->GetHeight();
  87. R=this->right->GetHeight();
  88. return 1+(L>R? L:R);
  89. }
  90. };
  91. #endif // BRTREENODE_H_INCLUDED
Copyright © Linux教程網 All Rights Reserved