← Reinforce Labs Interview Insights
My first instinct was to do a top-down DFS and I spent probably five minutes going down that path before realizing it doesn't work.
Use a post-order DFS to compute subtree stone sums, then for each internal node, determine the maximum child sum and add stones to the other children to match it. Accumulate these additions bottom-up, since balancing a subtree may change its total sum and affect ancestors.
Pro tip: Emphasize that you cannot simply equalize children to the maximum at each node independently—you must recompute subtree sums after balancing, and the greedy choice of raising to the max is optimal because stones can only be added.
Confirm that 'balanced' applies recursively to every internal node, and that adding stones to a node increases the total of all its ancestors. Ask about tree size and value ranges to choose an efficient approach.
Process children before parents so you can compute each subtree's total stone count after it has been internally balanced. Use recursion or an explicit stack to avoid recursion depth issues.
For each internal node, find the maximum child subtree sum, then add (max - childSum) stones to every other child subtree. Add these differences to a global counter and set the node's new subtree sum to its own stones plus the sum of balanced children.
Sum all additions made across all internal nodes. Because balancing a subtree changes its total, ensure the parent uses the updated sum when computing its own balancing.
State that the algorithm runs in O(n) time and O(h) space for a tree of n nodes and height h. Discuss edge cases like leaf-only trees, single-child internal nodes (always balanced), and large stone counts requiring 64-bit integers.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.