Assume you have a generic k-ary tree like this one or this one
Repeating the latter here:
template <typename T>
struct TreeNode
{
T* DATA ; // data of type T to be stored at this TreeNode
vector< TreeNode<T>* > children ;
void insert( T* newData ) ;
// runs f on this and all children of this
void preorder( function<void (T*)> f )
{
f( this->DATA ) ; // exec f on this
for( int i = 0 ; i < children.size(); i++ )
children[i]->preorder( f ) ; // exec f on each child
}
} ;
template <typename T>
struct Tree
{
TreeNode<T>* root;
// TREE LEVEL functions
void clear() { delete root ; root=0; }
void insert( T* data ) { if(root)root->insert(data); }
} ;
Now normally, you have pre-order and post-order traversals as recursive member functions of TreeNode
as shown above. But say you don't want to be passing functions around, you want to visit each node in the tree from outside the class (ie just given a Tree
object).
How can you do it?