Collect Every File Path from a Nested Directory Tree
Trees & GraphsAuto-graded · 17 test casesLast updated
Traverse a nested directory dictionary depth-first and build the full slash-joined path for each file, following precise joining and ordering rules.
Collect Every File Path from a Nested Directory Tree
A file system is described as a nested dictionary. Each node has these keys:
name: a string, the name of this file or directory.isFile: a boolean,truefor a file andfalsefor a directory.children: a list of child nodes. It is empty for files, and it may be missing entirely, in which case treat it as empty.
The top-level dictionary is the root directory.
Write a function that returns the full path of every file in the tree, as a list of strings.
Path rules
- The path of the root is just its
name. - The path of any other node is
parent_path + "/" + name. - Exception: if
parent_pathis the empty string, the node's path is just itsname, with no leading/. - Names are used exactly as given. Do not trim, normalize, or collapse slashes. For example, a root named
"/"with a filefile.txtgives"//file.txt".
Output rules
- Include only files. Directories never appear in the output, and empty directories contribute nothing.
- Visit nodes depth-first in pre-order, handling each node's children in the order they are listed. Return the paths in the order the files are encountered.
- If the root itself is a file, return a list containing only its name.
Constraints
- The tree has at least one node (the root).
- Every node has a string
nameand a booleanisFile. - Files have no children.
- Names are arbitrary strings, possibly containing
/, and are used verbatim. - Recursion depth is modest, so a recursive DFS is acceptable.
Examples
Example 1
Input: collect_file_paths({'name': 'root', 'isFile': False, 'children': [{'name': 'a', 'isFile': False, 'children': [{'name': 'b.txt', 'isFile': True, 'children': []}, {'name': 'c', 'isFile': False, 'children': [{'name': 'd.md', 'isFile': True, 'children': []}]}]}, {'name': 'e.log', 'isFile': True, 'children': []}]})
Output: ['root/a/b.txt', 'root/a/c/d.md', 'root/e.log']
Example 2
Input: collect_file_paths({'name': '/', 'isFile': False, 'children': [{'name': 'file.txt', 'isFile': True, 'children': []}]})
Output: ['//file.txt']
Hints
Hint 1
Think of the path as something you carry down as you move from a node to its children, rather than something you rebuild from scratch.
Hint 2
At each node, compute its own path from the parent's path. If the node is a file, record the path and stop. Otherwise recurse into each child in order.
Hint 3
Watch the joining rule: when the parent path is empty, use the name alone. Do not strip or clean the root name, because a root of "/" must produce "//file.txt".
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Run a depth-first search from the root and pass the path built so far down to each child.
For each node:
- Compute its path. If the parent path is empty, the path is the node's name. Otherwise it is
parent_path + "/" + name. - If the node is a file, append its path to the result and return. Files are leaves.
- If the node is a directory, recurse into each child in the order listed, passing this node's path.
Why it is correct
A tree has exactly one route from the root to any node, so each file is reached exactly once. The path passed down always equals the joined names along that route, using the stated rule. Only file nodes append to the result, so directories and empty directories never appear. Processing children in listed order, with the node handled before its children, gives the required pre-order. The root name is never altered, so a root of "/" yields "//file.txt" as specified.
Complexity
- Time: O(N + L), where N is the number of nodes and L is the total length of the strings built along the way. In the worst case, building a path string at every node costs up to the sum of path lengths.
- Space: O(H) for the recursion stack, where H is the tree height, plus the output.
Reference solution
from typing import Dict, List
def collect_file_paths(tree: Dict) -> List[str]:
result = []
def dfs(node, path):
current_path = f"{path}/{node['name']}" if path else node['name']
if node['isFile']:
result.append(current_path)
return
for child in node.get('children', []):
dfs(child, current_path)
dfs(tree, "")
return result