Build a Visual Directory Tree from Nested Dictionary
Trees & GraphsAuto-graded · 14 test casesLast updated
Tests recursion, dictionary traversal, and string formatting to produce an indented tree structure with box-drawing connectors.
You are given a nested dictionary representing a filesystem structure and the name of the root directory. Your task is to generate a visual tree representation returned as a list of strings, where each string is one line of the tree.
Structure
- Files are represented by keys whose values are
None. - Directories are represented by keys whose values are dictionaries (possibly empty).
- Directory names in the output must end with a trailing
/.
Formatting Rules
- The first line is always the root directory name followed by
/. - Each subsequent entry uses tree-drawing characters:
├──when the entry has siblings below it.└──when the entry is the last child in its directory.
- Indentation for nested entries uses:
│(vertical bar + three spaces) to continue a line from an ancestor that has remaining siblings.(four spaces) when an ancestor was the last child.
- Entries within each directory must be sorted alphabetically (case-sensitive).
- Hidden entries (names starting with
.) must be excluded from the output entirely.
Constraints
1 ≤ len(root_name) ≤ 1000 ≤ total number of entries ≤ 1000- Entry names contain only alphanumeric characters, underscores, dots, and hyphens.
- The structure is acyclic (no circular references).
- Nesting depth will not exceed 50 levels.
Examples
Example 1
Input: build_tree_lines('root', {'config.json': None, 'src': {'index.js': None, 'utils.js': None}, 'README.md': None})
Output: ['root/', '├── README.md', '├── config.json', '└── src/', ' ├── index.js', ' └── utils.js']
Example 2
Input: build_tree_lines('project', {'empty': {}, 'visible.txt': None, '.git': {'config': None}})
Output: ['project/', '├── empty/', '└── visible.txt']
Hints
Hint 1
Think of this as a depth-first traversal where each directory's children are processed in sorted order.
Hint 2
The prefix string accumulates as you recurse deeper: add either a vertical bar with spaces or just spaces depending on whether the parent has more siblings.
Hint 3
Filter out hidden entries before sorting and before determining which child is last.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires a depth-first traversal of a nested dictionary structure while building formatted strings with proper indentation and tree-drawing characters.
The core insight is that each line consists of two parts:
-
Inherited prefix — carries the indentation context from all ancestor levels. Each ancestor contributes either
│(if it has remaining siblings) or(if it was the last child). -
Current connector — either
├──(has siblings below) or└──(last child).
The algorithm processes each directory by:
- Filtering out entries starting with
.(hidden files) - Sorting the remaining entries alphabetically
- Determining which is the last entry to choose the correct connector
- Recursively processing subdirectories with an extended prefix
When recursing into a child, the prefix extends by adding either │ or depending on whether the current node is the last sibling. This single rule produces correct output at any depth.
Why It Works
- Correct ordering: Sorting at each level ensures deterministic, alphabetical output within each directory.
- Proper connectors: The
is_lastflag accurately determines whether to use└──or├──. - Accurate vertical lines: A
│appears in column d exactly when the ancestor at depth d has unprocessed siblings remaining. - Hidden file handling: Filtering before determining
is_lastensures the last visible entry gets└──.
Complexity
Time: O(N log N) where N is the total number of entries. Each entry is visited once, and sorting costs are bounded by N log N across all directories.
Space: O(D × W) where D is maximum depth and W is maximum width (entries per directory). This accounts for the recursion stack, prefix strings, and temporary sorted lists.
Implementation
from typing import Dict, List, Optional
def build_tree_lines(root_name: str, entries: Dict[str, Optional[Dict]]) -> List[str]:
result = []
def traverse(name: str, structure: Optional[Dict], prefix: str, is_last: bool):
# Determine connector based on position
connector = "└── " if is_last else "├── "
if structure is None:
# It's a file
result.append(prefix + connector + name)
else:
# It's a directory
result.append(prefix + connector + name + "/")
# Filter out hidden entries (starting with .)
visible = {k: v for k, v in structure.items() if not k.startswith('.')}
# Sort alphabetically
sorted_items = sorted(visible.items())
# Build new prefix for children
extension = " " if is_last else "│ "
new_prefix = prefix + extension
# Recurse into children
for i, (child_name, child_structure) in enumerate(sorted_items):
is_last_child = (i == len(sorted_items) - 1)
traverse(child_name, child_structure, new_prefix, is_last_child)
# Start with root directory
result.append(root_name + "/")
# Filter hidden entries from root level
visible = {k: v for k, v in entries.items() if not k.startswith('.')}
# Sort root entries alphabetically
sorted_items = sorted(visible.items())
# Process each root-level entry
for i, (child_name, child_structure) in enumerate(sorted_items):
is_last_child = (i == len(sorted_items) - 1)
traverse(child_name, child_structure, "", is_last_child)
return result