← Reinforce Labs Interview Insights
My first instinct was top-down DFS and I spent a few minutes going down that path before realizing it doesn't work.
Use a post-order DFS to compute the total stones in each subtree. For each internal node, determine the maximum subtree sum among its children, then add stones to the other child subtrees to match that maximum. Accumulate the total additions and return the sum.
Pro tip: Clarify that the tree is rooted and that 'balanced' applies only to internal nodes, not leaves. Also, mention that the greedy choice of raising all children to the maximum is optimal because adding stones to the largest subtree would only increase the required additions elsewhere.
Confirm that only additions are allowed, each costing 1, and that the goal is to minimize total additions. Ensure you know the tree structure and that leaves are exempt from balancing.
Traverse the tree bottom-up, computing for each node the total stones in its subtree after balancing. For leaves, the total is just the node's stone count.
For an internal node, collect the balanced subtree sums of its children. Find the maximum among them, then add stones to each other child subtree to reach that maximum. Sum these additions.
Return the new total stones for the subtree (node's own stones plus the sum of balanced children sums) and accumulate the total additions across all internal nodes.
State that the algorithm runs in O(n) time and O(h) space for recursion. Discuss edge cases like single-node trees, skewed trees, and large stone counts.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.