Given a binary tree such as this:
#include <iostream>
template <typename InfoType>
struct Node
{
InfoType info;
Node<InfoType> *left;
Node<InfoType> *right;
};
template <typename InfoType>
class BinaryTree
{
public:
bool search(const InfoType& searchItem) const;
void insert(const InfoType& insertItem);
void delete(const InfoType& deleteItem);
void orderedPrint() const;
protected:
Node<InfoType> *root;
private:
void orderedPrint(Node<InfoType>* p) const;
};
template <typename InfoType>
void BinaryTree<InfoType>::orderedPrint() const
{
orderedPrint(root);
}
template <typename InfoType>
void BinaryTree<InfoType>::orderedPrint(Node<InfoType>* p) const
{
if (p != nullptr)
{
orderedPrint(p->left);
std::cout << p->info << " ";
orderedPrint(p->right);
}
}
how do I edit the class so that I can write something like this:
#include <vector>
int main()
{
std::vector<int> v;
BinaryTree<int> tree;
for (auto i: tree)
{
v.push_back(i);
}
return 0;
}
The idea is to be able to iterate through all the contents of a binary tree, similar to iterating through all the elements in a standard container.
Specifically, how do you write the iteration code (e.g., operator++()
) given the recursive nature of traversing the nodes?