我需要使用迭代算法来查找树中的元素数量,但是我发现该代码在概念上很难编写。
我的方法是从根节点开始并访问子节点,然后访问这些子节点的子节点,依此类推。
这是我编写的适用于一棵小树的代码,但这不是真正的解决方案,因为我需要为每个深度级别添加一个额外的块:
// Start the counter at 1 because the root node counts
int size = 1;
for(ITree child1 : root) {
size++;
for(ITree child2 : child1) {
size++;
for(ITree child3 : child2) {
size++;
for(ITree child4 : child3) {
size++;
for(ITree child5 : child4) {
size++;
}
}
}
}
}
return size;
从概念上讲,保留一个堆栈(LinkedList等)。对于每个孩子(现在,您的孩子循环),添加到堆栈中。继续循环遍历堆栈,直到最终将其清空为止。
这未经测试,但这应该可以完全满足您的要求。我只是使用java.io.File
而不是您的“ ITree”,因为它可以针对以下内容进行编译:
int sizeOfTree(File root){
// Start the counter at 1 because the root node counts
int size = 1;
LinkedList<File> stack = new LinkedList<File>();
stack.add(root);
while(!stack.isEmpty()){
File f = stack.remove();
for(File child : f.listFiles()){
size++;
stack.add(child);
}
}
return size;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句