My first instinct was to just do repeated DFS calls per node which is obviously O(n^2) and I caught myself before saying it out loud, barely.
Use a post-order DFS to compute subtree sums bottom-up: recursively compute the sum of each child's subtree, then add the node's own value to get its subtree sum. This visits each node once, achieving O(n) time and O(n) space for the recursion stack and result array.
Pro tip: Mention that for very deep trees, recursion might cause stack overflow, so you could use an iterative DFS with an explicit stack or increase recursion limit. Also, clarify that the tree is undirected, so you must avoid revisiting the parent during traversal.
Confirm that the tree is rooted at node 1, each node has an integer value, and you need to return an array of subtree sums. Ask about input format (adjacency list) and edge cases like n=1 or negative values.
Decide on a post-order DFS because subtree sums require children's sums before the parent's. Explain that this ensures each node is processed after its descendants.
Write a recursive function that takes a node and its parent, initializes sum to the node's value, then iterates over neighbors (excluding parent) and adds their returned sums. Return the total sum.
State that time complexity is O(n) because each node is visited once, and space complexity is O(n) for the recursion stack and result array. Discuss handling of large n and potential stack overflow.
Walk through a small tree (e.g., 1-2, 1-3) to verify correctness. Mention testing with negative values and a single node.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.