【发布时间】:2013-02-20 12:27:24
【问题描述】:
假设您有一个通用的 k-ary 树 like this one 或 this one
在这里重复后者:
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 对象) .
你是怎么做到的?
【问题讨论】:
-
您好我正在尝试使用 Java 实现其输出为相邻矩阵形式的 k 数组树。输入参数是 k = 每个节点的子节点数和 d = 树的深度。给定这个参数,我将生成树的相邻矩阵。我看到了github,无法关注。请您指导我实现这个吗?