Graph Theory37 sections · 1633 units
Open in Course

Contribution (What each subtree gives)

(Child contribution logic)

When you are at node uu, each child vv contributes down[v] to uu's answer. You combine all children's contributions to get down[u]. This is the down pass. For the up pass, you need to exclude child vv's contribution to compute up[v]. You cannot use down[u] directly because that already includes down[v].

You need down[u] minus down[v]. Trick: compute prefix and suffix products or sums of children's contributions. Then you can exclude any single child in O(1)O(1) time. This keeps the up pass linear.

Space complexity is O(n)O(n) for the data structures used.