Searching a file in a directory recursively using Post Order and InOrder preorder
When I write code to find a file in a directory recursively, for example, I use the following method:
public void list(File file) {
System.out.println(file.getName());
File[] children = file.listFiles();
for (File child : children) {
list(child);
}
}
If I need to show it in a preview, in order and after a work-around, how can I do that?
I cannot link tree traversal with this file search.
+3
source to share
2 answers
Your code is in preorder as the parent is processed (printed) before the children. If you moved the print after the loop, it will be post-order. It wouldn't make too much sense in that case. If you had a binary tree, it would be if you handled parent intermediate processing of each child.
+1
source to share
What you are doing is preliminary traversal.
This is the post-order workaround:
public void list(File file) {
if(file == null)return;
File[] children = file.listFiles();
for (File child : children) {
list(child);
}
System.out.println(file.getName());
}
And in a roundabout way, there is no natural definition for a generic tree
0
source to share