You need to implement the simplest container for the binary tree, define the begin (), end () functions and reload the ++ and * operators for the iterator. To navigate through the elements, I decided to write tree nodes to the STL-list and move the iterator along it. The leftmost element of the tree is considered the beginning of the container, the element beyond the rightmost one is the end of the container.
template <typename T> class Node { private: T data; Node<T> *left, *right; bool flag; friend class Tree<T>; public: Node(): flag(false), left(NULL), right(NULL){} ~Node(){if(left){delete left; left = NULL;} if(right){delete right; right = NULL;}} }; template <typename T> class Tree { private: friend class Iterator; Node<T>* head; public: class Iterator { private: list<Node<T> > li; typename std::list<Node<T> >::iterator li_it; void build(Node<T>*); public: Iterator(); ~Iterator(); Iterator(const Iterator&); Iterator& operator ++ (); T& operator * (); };
The problem is that if changes occur in the tree (add / delete a node), then the entire list will have to be rebuilt. That is, I must at any time have access to the tree itself or to its root. What can be done in this case?
O(N)
memory for a tree ofN
elements. Try to copy it somewhere in theperformance-critical
code section. - Costantino RupertSTL
tree
containers. As a good reference, I can offer you [iterator descriptiontree.hh
] [1] [1]: tree.phi-sci.com/tree.pdf - Costantino Rupert