title: How can you iterate a k-ary tree?
body: <p>Assume you have a generic k-ary tree <a href="http://vivin.net/2010/01/30/generic-n-ary-tree-in-java/" rel="nofollow noreferrer">like this one</a> or <a href="https://stackoverflow.com/questions/205945/why-does-the-c-stl-not-provide-any-tree-containers/15230597#15230597">this one</a></p>
  
  <p>Repeating the latter here:</p>
  
  <pre><code>template &lt;typename T&gt;
  struct TreeNode
  {
    T* DATA ; // data of type T to be stored at this TreeNode
  
    vector&lt; TreeNode&lt;T&gt;* &gt; children ;
  
    void insert( T* newData ) ;
  
    // runs f on this and all children of this
    void preorder( function&lt;void (T*)&gt; f )
    {
      f( this-&gt;DATA ) ; // exec f on this
      for( int i = 0 ; i &lt; children.size(); i++ )
        children[i]-&gt;preorder( f ) ; // exec f on each child
    }
  
  } ;
  
  template &lt;typename T&gt;
  struct Tree
  {
    TreeNode&lt;T&gt;* root;
  
    // TREE LEVEL functions
    void clear() { delete root ; root=0; }
  
    void insert( T* data ) { if(root)root-&gt;insert(data); } 
  } ;
  </code></pre>
  
  <p>Now normally, you have pre-order and post-order traversals as recursive member functions of <code>TreeNode</code> as shown above.  <strong>But say you don't want to be passing functions around</strong>, you want to visit each node in the tree <em>from outside</em> the class (ie just given a <code>Tree</code> object).</p>
  
  <p>How can you do it?</p>