これまたはこれのような一般的な k-ary ツリーがあるとします。
ここで後者を繰り返します:
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); }
} ;
TreeNode
通常、上記 のように の再帰メンバー関数として、事前注文と事後注文のトラバーサルがあります。しかし、関数を渡したくない場合は、ツリー内の各ノードにクラスの外からアクセスしたいとします(つまり、Tree
オブジェクトを指定しただけです)。
どうすればできますか?