图--广度优先遍历/深度优先遍历的一些理解
package cn.it;
import java.io.File;
import java.util.LinkedList;
import java.util.Queue;
public class FileUtil {
public static void main(String[] args) {
File root = new File("/usr/local/soft_pack/book");
showFile_ByDFS(root);
System.out.println("================================\n\n\n");
root = new File("/usr/local/soft_pack/book_book");
Queue<File> queue = new LinkedList<File>();
queue.offer(root);
showFile_ByBFS(root, queue);
}
// 深度优先遍历(DFS) --利用递归实现(打破砂锅问到底)
public static void showFile_ByDFS(File root) {
if (root.isFile()) {
System.out.println(root.getName());
return;
}
if (root.isDirectory()) {
System.out.println(root.getName());
File[] files = root.listFiles();
for (int i = 0; i < files.length; i++) {
showFile_ByDFS(files[i]);
}
}
}
// 广度优先遍历(BFS) -- 利用队列实现(先进先出FIFO)
public static void showFile_ByBFS(File root, Queue<File> fileQueue) {
while (!fileQueue.isEmpty()) {
File fileroot = fileQueue.poll();
System.out.println(fileroot.getName());
if (fileroot.isDirectory()) {
File[] files = fileroot.listFiles();
for (int i = 0; i < files.length; i++) {
fileQueue.offer(files[i]);
}
}
}
}
}