← Questions

Print a directory tree with indentation

0
UberCodingLast asked Oct 2025

A coding interview question asked in Uber's technical phone screen, last asked Oct 2025. It tests trees, recursion and file systems.

You get the root of a file system tree. Each node is a directory, which can have children, or a file, which has none. Print the whole tree starting from the root, one entry per line, with indentation showing depth: the root has no indent, and each level below it adds one more copy of an indentation marker. Children are printed in the order given.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • render_tree(root: Node, marker: str = "-> ") -> list[str] — Node has name: str and children: list[Node] (empty for files and empty directories). Returns the lines in pre-order; a line at depth d is marker * d + name.

Example

render_tree(dir)  ->
dir
-> subdir1
-> -> file1.ext
-> -> subsubdir1
-> subdir2
-> -> subsubdir2
-> -> -> file2.ext

render_tree(root, marker="  ")  ->  ["root", "  file"]     # root holds one file

Constraints

  • The input is a tree: no cycles, every node has one parent.
  • Up to 10^5 nodes; the tree can be very deep.

Clarifying questions

  • Print to stdout or return the lines?
  • Should children be sorted, or kept in the given order? Directories before files?
  • How is a directory told apart from a file, for example an empty directory?
  • What marker and spacing exactly? Is the output compared character for character?

What a strong answer covers

  • A pre-order DFS carrying the depth, printing each node before its children.
  • An iterative version with an explicit stack (pushing children in reverse to keep their order) for very deep trees.
  • Building lines without quadratic string work, for example by reusing a prefix per depth.
  • O(n) nodes visited; output size dominates.
  • Tests: a single file as root, empty directories, deep nesting, a custom marker.

Follow-ups

  • Draw the tree with ├──, └── and │ connectors like the tree command.
  • Add each directory's total size, computed from its files.
  • Build the tree from a flat list of paths such as "dir/subdir1/file1.ext".
  • The tree comes from the real file system and may contain symbolic links that form cycles.

Where it's asked

  • Uber · Technical phone screen · Last asked Oct 202560 min · One medium problem with a follow-up, or two short ones; sometimes object-oriented design

What it tests

trees · recursion · file systems

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding