Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Recursion

    Recursion on Structures: Nested Folders

    A folder can contain notes and other folders. A folder is defined in terms of folders. When a structure is defined by containing smaller copies of itself, the

    Chapter 4 of 94 min readOften asked in interviews

    The Plain Picture#

    A folder can contain notes and other folders. A folder is defined in terms of folders. When a structure is defined by containing smaller copies of itself, the code that walks it writes itself: handle this folder, then do the same to each folder inside.

    The Real Names#

    A structure that contains smaller structures of the same kind is recursive (or self-similar). The folder tree is a tree: one root, each node with zero or more children, no loops (trees in depth: Binary Trees and Binary Search Trees (coming soon)). Walking every node of a tree by going as deep as possible first is depth-first traversal — the same idea as depth-first search on graphs (Graphs I (coming soon)).

    Under the Hood — solving Part 0#

    Java
    record Folder(String name, List<String> notes, List<Folder> subfolders) {}
    
    static int countNotes(Folder f) {
        int total = f.notes().size(); // my own notes
        for (Folder sub : f.subfolders()) {
            total += countNotes(sub); // leap of faith: each subfolder's full count
        }
        return total;
    }

    Where's the base case? A folder with no subfolders: the loop runs zero times and the method just returns its own count. The base case is hidden in the empty loop — very common in tree recursion.

    Printing the tree with indentation (the depth tells us how far to indent):

    Java
    static void printTree(Folder f, int depth) {
        System.out.println(
            "  ".repeat(depth) + f.name() + "/ (" + f.notes().size() + " notes)"
        );
        for (Folder sub : f.subfolders()) printTree(sub, depth + 1);
    }
    Output
    Semester1/ (1 notes)
      Biology/ (2 notes)
        Lab/ (3 notes)
      Chemistry/ (1 notes)
        Organic/ (0 notes)
          Exams/ (1 notes)
    notes (recursive) = 8

    It handles any depth without knowing it in advance — the problem loops couldn't solve.

    Pre-order vs post-order: printTree does its work (printing) before recursing into children — pre-order. countNotes combines children's results after they return — effectively post-order. (Chapter 2's rule again: before the call = on the way down; after = on the way up.) Deleting a folder must be post-order — you delete the contents before the folder itself.

    The same shape covers real problems: the size of a directory on disk, rendering nested comments, evaluating (2 + (3 × 4)), the HTML DOM tree (The DOM, Events and Browser APIs (coming soon)), and JSON parsing.

    Check yourself

    3 questions
    1

    Where is the base case in countNotes?

    Show answer

    A folder with no subfolders — the loop doesn't run and it returns its own note count.

    2

    Pre-order vs post-order — which is printTree, and why must "delete folder" be the other one?

    Show answer

    printTree is pre-order (work before the recursive calls). Deletion must be post-order: contents must be removed before the folder that holds them.

    3

    Write maxDepth(Folder f): 1 for a folder with no subfolders, otherwise 1 + the deepest subfolder.

    Show answer

    int best = 0; for (Folder s : f.subfolders()) best = Math.max(best, maxDepth(s)); return 1 + best; (Semester1 → 4.)