Skip to content

Commit f6abe96

Browse files
committed
Add simple forward iterator to bst
1 parent f94951a commit f6abe96

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

include/mystd/some_trees/bst.hpp

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,48 @@ class binary_search_tree {
372372
return new_root;
373373
}
374374

375+
public:
376+
// inorder forward iterator (left -> vert -> right)
377+
template <bool IsConst>
378+
class iterator_basic {
379+
private:
380+
Node* current;
381+
382+
public:
383+
iterator_basic(Node* n = nullptr) : current(n) {}
384+
385+
value_type& operator*() { return current->data; }
386+
387+
value_type* operator->() { return &(current->data); }
388+
389+
iterator_basic& operator++() {
390+
if (!current) {
391+
return *this;
392+
}
393+
if (current->right) {
394+
current = current->right;
395+
while (current->left) {
396+
current = current->left;
397+
}
398+
} else {
399+
Node* p = current->parent;
400+
while (p && current == p->right) {
401+
current = p;
402+
p = p->parent;
403+
}
404+
current = p;
405+
}
406+
return *this;
407+
}
408+
409+
bool operator==(const iterator_basic& other) const { return current == other.current; }
410+
411+
bool operator!=(const iterator_basic& other) const { return current != other.current; }
412+
};
413+
414+
using iterator = iterator_basic<false>;
415+
using const_iterator = iterator_basic<true>;
416+
375417
public:
376418
binary_search_tree() noexcept = default;
377419

@@ -422,6 +464,21 @@ class binary_search_tree {
422464
void erasei(const Key& key) { root = delete_iterative(root, key); }
423465

424466
void swap(binary_search_tree& other) noexcept { std::swap(root, other.root); }
467+
468+
// iterators
469+
470+
iterator begin() {
471+
Node* n = root;
472+
if (!n) {
473+
return iterator(nullptr);
474+
}
475+
while (n->left) {
476+
n = n->left;
477+
}
478+
return iterator(n);
479+
}
480+
481+
iterator end() { return iterator(nullptr); }
425482
};
426483

427484
} // namespace my

tests/unit_tests/some_trees/test_bst.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,4 +110,24 @@ TEST(BSTTest, InsertDuplicateReplacesValue) {
110110
EXPECT_EQ(t.at(1), "uno");
111111
}
112112

113+
TEST(BSTTest, Iterators) {
114+
my::binary_search_tree<int, std::string> t;
115+
t.insert({5, "five"});
116+
t.insert({3, "three"});
117+
t.insert({7, "seven"});
118+
t.insert({6, "six"});
119+
t.insert({8, "eight"});
120+
121+
auto it = t.begin();
122+
auto ite = t.end();
123+
124+
EXPECT_EQ((*it).second, "three");
125+
126+
std::vector<int> answer = {3, 5, 6, 7, 8};
127+
int i = 0;
128+
for (const auto& n : t) {
129+
EXPECT_EQ(n.first, answer[i++]);
130+
}
131+
}
132+
113133
} // namespace my::testing

0 commit comments

Comments
 (0)