Back to problems

Compute subtree sums with tree DFS

Algorithm · Netflix · Medium

Consider a connected acyclic graph with n vertices numbered 1 through n, where vertex 1 is designated as the root. Each vertex i carries an integer val[i]. For any vertex u, its subtree consists of u itself plus every vertex that can be reached from u by moving away from the root. You are given n, a list edges containing n - 1 undirected pairs, and an array val of length n; val[i - 1] is the value attached to vertex i. Return an array ans of length n such that ans[i - 1]…

Checking your access…