Non-recursive way to list files in directory and subdirectories without using stack/queue

algorithm, queue, recursion, stack

Solution

In a depth-first search note that the current path essentially serves as a stack. Listing names in a depth-first manner, proceed like you would expect but don't bother recording a stack... When you're done listing files in a directory, you can 'pop' the stack by noting what the last directory was that you were in and then continue from that point in the parent directory.

Problem

During an interview, I was asked to list the names of files in a directory and its subdirectories¹ without using neither recursion, nor stack or queue. Since the only non-recursive way I know uses a stack, I was unable to answer this question. The interviewer explained the solution, but I was unable to understand it. The only thing I remember is that it involved two methods instead of one. What is this approach which allows listing files in a directory and its subdirectories with no recursion and no stack or queue? ¹ The solution is language agnostic. The list of subdirectories is provided by a `ListDirectories(string directoryPath)` method, and the files - by `ListFiles(string directoryPath)`. We don't know in advance the depth of subdirectories.

Original source