-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIterator.cpp
More file actions
139 lines (120 loc) · 2.92 KB
/
Iterator.cpp
File metadata and controls
139 lines (120 loc) · 2.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/**
* @cite Iterator Pattern states that when a data structure needs to be traversed on the client-side, then an iterator API needs to be provided that simplifies the traversal process.
*
* @brief Iterator Pattern can be exemplified by a Binary Tree data structure that needs to be traversed.
*/
#include <iostream>
#include <vector>
/**
* @brief Node of a Binary Tree with left-child, right-child and parent Node ptrs.
*/
template <typename T>
struct Node
{
Node<T> *left{nullptr}, *right{nullptr}, *parent{nullptr};
T value = T();
Node(T val,
Node<T> *left = nullptr,
Node<T> *right = nullptr) : left(left), right(right), value(val)
{
if (left)
left->parent = this;
if (right)
right->parent = this;
}
~Node()
{
if (left)
delete left;
if (right)
delete left;
}
};
/**
* @brief Binary Tree class that represents a binary tree and provide traversal funtionality using iterators.
*/
template <typename T>
class BinaryTree
{
Node<T> *root{nullptr};
public:
BinaryTree(Node<T> *t) : root(t) {}
~BinaryTree() { delete root; }
// Iterator Class that iterates over the Binary Tree.
template <typename U>
class InOrderIterator;
typedef InOrderIterator<T> iterator;
// for range-based loops
iterator begin()
{
Node<T> *curr = root;
while (curr && curr->left)
{
curr = curr->left;
}
return iterator(curr);
}
// for range-based loops
iterator end()
{
return iterator{nullptr};
}
};
template <typename T>
template <typename U>
class BinaryTree<T>::InOrderIterator
{
Node<U> *current;
public:
InOrderIterator(Node<U> *node) : current(node) {}
bool operator!=(const InOrderIterator<U> &it)
{
return it.current != current;
}
Node<U> &operator*() { return *current; }
InOrderIterator<U> &operator++()
{
if (current->right)
{
current = current->right;
while (current->left)
{
current = current->left;
}
}
else
{
Node<U> *p = current->parent;
while (p && current == p->right)
{
current = p;
p = p->parent;
}
current = p;
}
return *this;
}
};
int main()
{
/**
* 43
* / \
* 45 83
* / \ \
*32 46 21
*/
BinaryTree<int> bt{
new Node<int>{43,
new Node<int>{45,
new Node{32},
new Node{46}},
new Node<int>{83,
nullptr,
new Node{21}}}};
for (auto &node : bt)
{
std::cout << node.value << " ";
}
return 0;
}