Compute subtree sums with tree DFS
Company: Netflix
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in tree traversal and aggregation techniques, specifically computing subtree sums using depth-first search while handling traversal state and constraints such as negative values and large n.
Constraints
- 1 <= n <= 2 * 10^5
- len(edges) == n - 1
- -10^9 <= val[i] <= 10^9
- The input graph is guaranteed to be a tree
- Values may be negative
Examples
Input: (5, [(1, 2), (1, 3), (3, 4), (3, 5)], [4, 2, 1, 3, 5])
Expected Output: [15, 2, 9, 3, 5]
Explanation: Node 3 has subtree {3,4,5} with sum 1+3+5=9. Node 1 includes all nodes, so its sum is 15.
Input: (4, [(1, 2), (2, 3), (2, 4)], [1, -2, 4, -1])
Expected Output: [2, 1, 4, -1]
Explanation: Node 2 has subtree sum -2+4+(-1)=1, and node 1 has 1+1=2.
Input: (1, [], [-7])
Expected Output: [-7]
Explanation: A single node's subtree consists only of itself.
Input: (6, [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)], [5, 0, -2, 1, 1, 1])
Expected Output: [6, 1, 1, 3, 2, 1]
Explanation: This is a chain. Compute from the end upward: node 6=1, node 5=2, node 4=3, node 3=1, node 2=1, node 1=6.
Input: (4, [(1, 2), (1, 3), (1, 4)], [0, 0, 0, 0])
Expected Output: [0, 0, 0, 0]
Explanation: All node values are zero, so every subtree sum is zero.
Hints
- Build an adjacency list for the tree, then run DFS from node 1 while tracking each node's parent.