Introduction
Refer to the 'FolderTree.rar' in the 'Download Files' section above for the code.
In this blog, I will demonstrate Java code to print the folder tree or folder hierarchy or what you can call a directory structure.
I have used class objects array as a data structure to store the information regarding the folders. An Array List of integers is used to store visited indexes and a variable named ‘tab’ to give tab spaces.
- First, it asks to enter the number of folders and we enter the number of folders.
- For each folder, we enter Folder ID, folder’s Parent ID and Folder name.
- After entering these details for each folder, the folder hierarchy gets displayed.
I have used a recursive function for printing this hierarchy. Let’s understand the flow. Consider the following hierarchy:
So, according to this, we will design table like,

| Folder ID | Parent Folder ID | Folder Name |
| 1 | 0 | Gujarat |
| 2 | 0 | Maharashtra |
| 3 | 1 | Ahmedabad |
| 4 | 1 | Surat |
| 5 | 2 | Mumbai |
| 6 | 5 | Colaba |
| 7 | 2 | Pune |

Join the conversation! Your thoughts help the community grow.