我正在尝试实现一个从根到下计算树中所有节点的方法。基本上,我计算根数,然后添加每个根子列表的长度。
public int size()
{
int count = 1; //count the root node
for (int i = 0; i < root.getChildren().size(); i++){
count += (root.getChildren().get(i)).length() + 1;
}
return count;
}这是已解决的解决方案。
发布于 2010-10-14 13:43:42
您可以将size()方法实现为ArrayTreeNode的成员。使用递归。节点的大小是1加子节点大小之和。
所以在你的size()方法中有两种情况:
顺便说一句。为什么在类ArrayTree中既有tree属性又有root属性?根节点还不够吗?为什么要有一个单独的ArrayTree类呢?ArrayTreeNode本身已经是一棵树了。
在哪里设置ArrayTreeNode类的parent属性?如果在addChild()方法中设置父级以确保parent始终有效,这不是最好的吗?
更新:
好的,你要的是一个例子。我认为如果你不习惯递归,你就不会那么容易理解它。
这是类ArrayTreeNode的方法
public int size() {
int sum = 1; // Count at least this node
// Ask every child for its size. If this node is a leaf,
// then no recursive call happens.
// Otherwise call the size() method recursively for ervery
// child node. The child's size() method may also call its
// own childs size() method, adding another level of recursion.
// But we can be sure that the recursion comes to an end because
// at every leaf the simple answer will be 1.
for(ArrayTreeNode<E> child: children) {
sum += child.size();
}
// return our calculated size.
return sum;
}https://stackoverflow.com/questions/3929915
复制相似问题