我需要创建应用程序,它使用非递归遍历文件系统并打印出特定深度的文件。 我有什么:Java非递归文件系统步行
public void putFileToQueue() throws IOException, InterruptedException {
File root = new File(rootPath).getAbsoluteFile();
checkFile(root, depth);
Queue<DepthControl> queue = new ArrayDeque<DepthControl>();
DepthControl e = new DepthControl(0, root);
do {
root = e.getFileName();
if (root.isDirectory()) {
File[] files = root.listFiles();
if (files != null)
for (File file : files) {
if (e.getDepth() + 1 <= depth && file.isDirectory()) {
queue.offer(new DepthControl(e.getDepth() + 1,file));
}
if (file.getName().contains(mask)) {
if (e.getDepth() == depth) {
System.out.println(Thread.currentThread().getName()
+ " putting in queue: "
+ file.getAbsolutePath());
}
}
}
}
e = queue.poll();
} while (e != null);
}
和辅助类
public class DepthControl {
private int depth;
private File file;
public DepthControl(int depth, File file) {
this.depth = depth;
this.file = file;
}
public File getFileName() {
return file;
}
public int getDepth() {
return depth;
}
}
我收到的答案,这个程序使用,因为广度优先搜索(希望右平移)的额外内存。我有O(k^n),其中k - 平均数量的子目录,n - 深度。这个程序可以用O(k * n)轻松完成。请帮我修复我的算法。
为什么它必须非递归? – 2012-03-07 17:30:10
@HotLicks,这可能是一个家庭作业相关的要求。 – Moonbeam 2012-03-07 17:32:34
为了复杂化,我想。这是面试任务。 – user1255246 2012-03-07 17:35:00