Guest User

Untitled

a guest
Apr 23rd, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. #if !defined(BST_H)
  2. #define BST_H
  3.  
  4. #include <string>
  5. #include <utility>
  6. #include <stack>
  7.  
  8. template <class Key, class Value>
  9. class BST {
  10. class Node;
  11.  
  12. public:
  13. class Iterator {
  14. public:
  15. Iterator(Node * root) {
  16. if (!root) {
  17. current_ = nullptr;
  18. return;
  19. }
  20. leftmost(root);
  21. current_ = stack.top();
  22. stack.pop();
  23. }
  24.  
  25. bool operator==(const Iterator& other) {
  26. return current_ == other.current_;
  27. }
  28.  
  29. bool operator!=(const Iterator& other) {
  30. return current_ != other.current_;
  31. }
  32. Iterator& operator++() {
  33. leftmost(current_->right());
  34.  
  35. if (stack.empty()) {
  36. current_ = nullptr;
  37. return *this;
  38. }
  39.  
  40. current_ = stack.top();
  41. stack.pop();
  42. return *this;
  43. }
  44.  
  45. const std::pair<const Key&, Value&> operator*() {
  46. return std::pair<const Key&, Value&>(current_->key(), current_->value());
  47.  
  48. }
  49.  
  50. private:
  51. void leftmost(Node* p) {
  52. while (p) {
  53. stack.push(p);
  54. p = p->left();
  55. }
  56. }
  57.  
  58. Node * current_; //Node to keep track
  59. std::stack<Node*> stack;
  60.  
  61. };
  62.  
  63. BST(){
  64. root_ = nullptr;
  65. }
  66.  
  67. Value& operator[](const Key& newKey) {
  68. if (root_ == nullptr) {
  69. root_ = new Node(newKey);
  70. return root_->value();
  71. }
  72. return root_->lookup(newKey);
  73.  
  74. }
  75.  
  76. Iterator begin() {
  77. return Iterator(root_);
  78.  
  79. }
  80.  
  81. Iterator end() {
  82. return Iterator(nullptr);
  83. }
  84.  
  85. private:
  86. class Node {
  87.  
  88. public:
  89. Node(Key newKey) : key_(newKey), value_(), left_(nullptr), right_(nullptr) {}
  90.  
  91. Value& value(){return value_;}
  92. const Key& key() {return key_;}
  93.  
  94. Value& lookup(const Key& aKey) {
  95. if (aKey == key_) {
  96. return value(); //can replae value(), left(), etc with value_, left_
  97. }
  98.  
  99. if (aKey < key_) {
  100. if (left_ == nullptr) {
  101. left_ = new Node(aKey);
  102. return left_->value();
  103. }
  104. return left_->lookup(aKey);
  105.  
  106. } else if (aKey > key_) {
  107. if (right_ == nullptr) {
  108. right_ = new Node(aKey);
  109. return right_->value();
  110. }
  111. return right_->lookup(aKey);
  112. }
  113. return value();
  114. }
  115.  
  116. Node* left() {
  117. return left_;
  118. }
  119.  
  120. Node* right() {
  121. return right_;
  122. }
  123.  
  124. private:
  125. const Key key_;
  126. Value value_;
  127. Node * left_;
  128. Node * right_;
  129. };
  130.  
  131. Node * root_;
  132. };
  133. #endif
Add Comment
Please, Sign In to add comment