RedBlackTree.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #pragma once
  2. // http://web.mit.edu/~emin/www/source_code/cpp_trees/index.html
  3. class RedBlackTreeNode
  4. {
  5. public:
  6. typedef int key_t;
  7. typedef void *val_t;
  8. friend class RedBlackTree;
  9. public:
  10. RedBlackTreeNode();
  11. RedBlackTreeNode(key_t, val_t);
  12. val_t GetEntry() const;
  13. ~RedBlackTreeNode();
  14. protected:
  15. val_t storedEntry;
  16. key_t key;
  17. int red; /* if red=0 then the node is black */
  18. RedBlackTreeNode *left;
  19. RedBlackTreeNode *right;
  20. RedBlackTreeNode *parent;
  21. };
  22. class RedBlackTree;
  23. class RedBlackTreeIterator
  24. {
  25. public:
  26. friend RedBlackTree;
  27. typedef int key_t;
  28. typedef void *val_t;
  29. RedBlackTreeIterator() : node(0), tree(0) {}
  30. RedBlackTreeIterator(RedBlackTreeNode *_node, RedBlackTree *_tree) : node(_node), tree(_tree) {}
  31. void next();
  32. bool get(val_t *val);
  33. private:
  34. RedBlackTreeNode *node;
  35. RedBlackTree *tree;
  36. };
  37. class RedBlackTree
  38. {
  39. public:
  40. typedef int key_t;
  41. typedef void *val_t;
  42. public:
  43. RedBlackTree();
  44. ~RedBlackTree();
  45. RedBlackTreeIterator end();
  46. RedBlackTreeIterator Insert(key_t, val_t);
  47. RedBlackTreeIterator Search(key_t key);
  48. RedBlackTreeIterator begin();
  49. // semi-public:
  50. void Delete(key_t key);
  51. val_t DeleteNode(RedBlackTreeNode *);
  52. RedBlackTreeNode *GetPredecessorOf(RedBlackTreeNode *) const;
  53. RedBlackTreeNode *GetSuccessorOf(RedBlackTreeNode *) const;
  54. size_t size() const;
  55. //TemplateStack<RedBlackTreeNode *> * Enumerate(int low, int high) ;
  56. protected:
  57. /* A sentinel is used for root and for nil. These sentinels are */
  58. /* created when RedBlackTreeCreate is caled. root->left should always */
  59. /* point to the node which is the root of the tree. nil points to a */
  60. /* node which should always be black but has aribtrary children and */
  61. /* parent and no key or info. The point of using these sentinels is so */
  62. /* that the root and nil nodes do not require special cases in the code */
  63. RedBlackTreeNode *root;
  64. RedBlackTreeNode *nil;
  65. void LeftRotate(RedBlackTreeNode *);
  66. void RightRotate(RedBlackTreeNode *);
  67. void TreeInsertHelp(RedBlackTreeNode *);
  68. void TreePrintHelper(RedBlackTreeNode *) const;
  69. void FixUpMaxHigh(RedBlackTreeNode *);
  70. void DeleteFixUp(RedBlackTreeNode *);
  71. size_t numElements;
  72. };