Equalize Adjacent Node Stones on a Tree (Add Only)

viaLeetCode

Problem: Given a tree with n nodes, each node already has a number of stones assigned (possibly zero). You may only add stones (never remove). Add the minimum total number of extra stones so that for every edge (u, v), |stones[u] - stones[v]| == 1.

Constraints: Tree with n nodes, n-1 edges, non-negative initial stone counts.

Approach: Root the tree and process it with a DFS/BFS (e.g. level order), since the constraint |stones[u]-stones[v]|==1 combined with "add only" means each node's final value is determined relative to its parent: for each child, its final stone count must be parent's final value ± 1, and since we can only add, take the larger of (parent+1) or the child's forced minimum, propagating downward and accumulating total additions needed level by level.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account