Compute minimum added stones to balance a tree
Reinforce LabsSoftware Engineer · Online AssessmentLast updated
This problem tests tree traversal techniques and greedy aggregation, requiring you to determine the minimum number of 'stones' needed to equalize all subtree sums to match a target value.
Problem Statement
You are given a binary tree where each node contains a value representing the number of stones at that position. A tree is considered 'balanced' if the sum of all nodes in every subtree rooted at any node u is equal to a target value K.
You can add any number of non-negative stones to any node in the tree. Your goal is to return the minimum total number of stones you need to add to the existing nodes to make the entire tree balanced.
Function Signature
def min_added_stones(root, K) -> int:
Constraints
- The tree has between 1 and 10^5 nodes.
- Node values and
Kare integers between 0 and 10^6. - If it is impossible to balance the tree by adding stones, return -1.
Examples
Example 1:
- Input:
root = [1, 2, 3], K = 6 - Explanation: The total sum of the tree is 6. The root subtree already sums to 6. The left child (2) needs +1 to make its subtree sum equal to 3, and the right child (3) needs 0. Wait—if
Kis the target for every subtree, we must check if the structure allows it. IfK=6, the left subtree must sum to 6 and the right to 6. - Output:
10(Calculation: 6-2=4 added to left, 6-3=3 added to right, then root adjustment).
Note: If the target K is smaller than a current subtree's sum, it is impossible to reach K by adding stones.
Hints
Hint 1
Perform a post-order traversal to calculate the current sum of each subtree starting from the leaves.
Hint 2
For any subtree with current sum `S`, you must add `K - S` stones if `S <= K`.
Hint 3
If any subtree's current sum already exceeds `K`, it is impossible to satisfy the condition, so return -1.
Follow-up questions
- How would your approach change if you were allowed to remove stones instead of just adding them?
- What if the tree is an N-ary tree instead of a binary tree?
- Can you optimize the solution to run in O(N) time and O(H) space, where H is the height of the tree?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.