← 返回 google 的题目列表Compute Total Size of a File System (Tree/Graph)
类型:online_judge
Given a file system hierarchy, compute the total size starting from a given root directory.
Each node is either a directory or a file:
A file has a non-negative integer size.
A directory has a list of child nodes.
During the interview it was clarified as a strict tree: every node has at most one parent, the structure reachable from the root is acyclic.
Implement a function that returns the total size of the root directory: the sum of sizes of all reachable files.
Input (typical abstraction)
root: a reference/ID of the root directory node.
You can access children for directories and size for files.
Output
An integer representing the total size.
Follow-ups
Analyze time and space complexity.
If repeated subtrees can be visited multiple times (e.g., due to shared references / hard-link-like semantics, though the final assumption is a tree), how would you use caching (memoization) to avoid recomputation?
Constraints
Number of nodes N can be up to 1e5.
Example
root dir contains file(10) and dirA; dirA contains file(5) and file(7)
Output: 22
Example
Input
root: dir -> [file(10), dirA]; dirA -> [file(5), file(7)]
Output
22