KatInterview

Render a Nested Folder Structure as Indented Lines

Trees & GraphsAuto-graded · 16 test cases
MediumAuto-gradedTrees & Graphstree-traversaldfsstack

Last 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) repeated depth times, 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 children list. 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.