Render a Nested Folder Structure as Indented Lines
Trees & GraphsAuto-graded · 16 test casesLast updated
Traverse a nested dictionary tree in pre-order, tracking depth to build indented lines with a fixed marker, preserving the given child order.
Render a Nested Folder Structure as Indented Lines
A folder hierarchy is given as a nested dictionary. Produce a text rendering of it, one entry per line, where the nesting level of each entry is shown by a repeated prefix.
Input
root is a dictionary describing a node:
"name": a string, the name of the entry."children"(optional): a list of node dictionaries nested directly inside this entry. A file normally omits this key, and an empty folder may give an empty list. Treat a missing key exactly like an empty list.
Output
Return a list of strings, one per node in the tree.
- Each string is the marker
"⟶ "(the arrow character followed by a single space) repeateddepthtimes, followed immediately by the node's name. - The root has depth 0, so its line is just its name with no prefix.
- A child's depth is its parent's depth plus one.
- Nodes appear in pre-order: a node's line comes first, then the lines for its whole subtree, and only then the line for its next sibling.
- Siblings keep the order in which they appear in the
childrenlist. Do not sort them. - Names are copied verbatim, with no trimming or escaping.
For instance, a node at depth 2 named a.txt produces the line ⟶ ⟶ a.txt.
Constraints
- The input is a valid tree: no node appears twice and there are no cycles.
- Every node has a
"name"string. - The tree may be deep, so avoid relying on deep recursion.
- The number of nodes is small enough for the full output to fit in memory.
Examples
Example 1
Input: render_folder_tree({'name': 'dir', 'children': [{'name': 'subdir1', 'children': [{'name': 'file1.ext'}, {'name': 'subsubdir1'}]}, {'name': 'subdir2', 'children': [{'name': 'subsubdir2', 'children': [{'name': 'file2.ext'}]}]}]})
Output: ['dir', '⟶ subdir1', '⟶ ⟶ file1.ext', '⟶ ⟶ subsubdir1', '⟶ subdir2', '⟶ ⟶ subsubdir2', '⟶ ⟶ ⟶ file2.ext']
Hints
Hint 1
Compare the expected output order with traversal types: a node is listed before its descendants, and a whole subtree is finished before the next sibling starts. Which traversal is that?
Hint 2
Depth is not stored in the input, so carry it along with each node, with a child's depth being its parent's depth plus one.
Hint 3
If you use an explicit stack to avoid recursion limits, remember it is last-in-first-out: push children in reverse order so the first child is processed first. Use a default of an empty list when `children` is missing.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The required line order is a pre-order depth-first traversal: a node is emitted, then everything beneath it, and only then its next sibling. The only extra information needed is each node's depth, which determines how many copies of the marker "⟶ " to put in front of its name.
To avoid Python's recursion limit on very deep trees, use an explicit stack of (node, depth) pairs:
- Push
(root, 0). - Pop a pair, append
"⟶ " * depth + nameto the result. - Read the node's children, using an empty list if the key is missing.
- Push the children in reverse order with depth
depth + 1. Because the stack is last-in-first-out, the first child is then popped first, so siblings keep their given order. - Repeat until the stack is empty.
Why it is correct
- Depth: the root is pushed with depth 0 and every child is pushed with its parent's depth plus one. By induction, each node's depth equals its distance from the root, so each prefix is right.
- Order: when a node is popped it is emitted immediately, and its children are placed on top of the stack above the node's later siblings. Its entire subtree is therefore emitted before those siblings. Reversed pushing places the first child on top, so children are visited left to right. This matches recursive pre-order exactly.
- Since the input is a tree, each node is reached exactly once, so no visited set is needed and the loop terminates.
Edge cases fall out naturally: a root with no children key yields a single line, an empty folder is rendered like a file, and sibling order is never altered.
Complexity
Let N be the number of nodes and L the total length of the output in characters.
- Time: O(N + L). Each node is pushed and popped once, and building each prefix costs time proportional to its length, which is part of the output size.
- Space: O(N) for the stack in the worst case (for example a root with many children), plus the output list.
Reference solution
from typing import Dict, List
def render_folder_tree(root: Dict) -> List[str]:
lines = []
stack = [(root, 0)] # (node, depth)
while stack:
node, depth = stack.pop()
lines.append("⟶ " * depth + node["name"])
children = node.get("children", [])
for child in reversed(children):
stack.append((child, depth + 1))
return lines