Problem 499372 · easy · Phase 04 Non-Linear Data Structures

Files in a Folder Tree

n-ary tree · DFS · counting

A file system is modelled as an N-ary tree of Node objects (val is the name, children is a list). Every node without children is a file; every other node is a folder. Return the number of files. An empty tree (None) has 0 files, and a single node counts as one file.

Examples

Input:  root = Node("root", [Node("docs", [Node("a.txt"), Node("b.txt")]), Node("readme")])
Output: 3
Explanation: a.txt, b.txt and readme have no children.

Input:  root = Node("x")
Output: 1

Constraints

  • 0 <= number of nodes <= 10**4, depth up to 1500
  • Target: O(n) time

Goals

  • Recognise leaves as nodes with an empty children list
  • Count while walking an N-ary tree with a stack
Starting Python…