I’ve written a code for searching a specific file , where the user enters a starting path and a filename , and then the program prints its details if the file exists , or prints not found otherwise.
As I suspected , the using of recursion makes the code to crash when the hierarchy tree is too large ,I’ve tried with 400 directories and it failed ,so I guess that after something like 50 folders one inside to other ,the overhead of the recursion makes the code to crash .
Any suggestions how to fix that ? basically the code is okay for low level tree hierarchy , but I need to design it for healthy trees (500-600 folders one inside the other , and a file that is stored at the last folder) also , thanks
You can remove the recursion (i.e. convert to an iterative solution) by storing the directories as you see them (instead of processing them immediately) and then coming back around to them on some later iteration. However, you might not get precisely identical output (things may be ordered differently).
The way this method works is by having a list of directories to process, and you go through this list (adding any child directories to it as you go).
In psuedocode/Python:
A stack can be implemented as a singly linked list fairly easily. Note that special handling is required if
pathis not a directory, and that this isn’t recursive.