Minimum Additions to Equalize Every Subtree Sum
Trees & GraphsModel answerLast updated
Calculate the minimum non-negative value additions needed so that the node sum of every subtree in a binary tree equals K, returning -1 if impossible.
You are given the root of a binary tree where each node holds a non-negative integer weight. A tree is considered subtree-uniform with target $K$ if every single node $u$ in the tree satisfies the following condition: the sum of all node weights in the subtree rooted at $u$ is exactly equal to $K$.
You are allowed to increase the weight of any node by adding a non-negative integer. You cannot decrease any node's weight.
Write a function that calculates the minimum total weight that must be added across all nodes to make the entire tree subtree-uniform with target $K$. If it is impossible to achieve this state by only adding non-negative values, return -1.
Function Signature
def min_additions_to_balance(root: Optional[TreeNode], K: int) -> int:
Input & Constraints
- The tree contains between $1$ and $10^5$ nodes.
- Each node's initial weight and $K$ are integers in the range $[0, 10^6]$.
- If balancing is impossible, return
-1.
Examples
Example 1:
- Input:
root = [1, 2, 3],K = 6 - Output:
-1 - Explanation: To make the left leaf (2) sum to 6, we must add 4. To make the right leaf (3) sum to 6, we must add 3. However, once both subtrees evaluate to 6, the root's total subtree sum becomes
1 (root) + 6 (left) + 6 (right) = 13. Since 13 exceeds $K = 6$ and we can only add positive weights, it is impossible to balance this tree.
Example 2:
- Input:
root = [0, 3, null],K = 5 - Output:
2 - Explanation: The leaf holds a weight of 3, so we add 2 to make its subtree sum 5. The root has 0 and a single child whose subtree sums to 5, making the root's sum already 5. The total weight added is 2.
Hints
Hint 1
Work from the bottom up: the required sum for every child subtree is rigidly fixed to K.
Hint 2
Consider what equation must hold at any node u with c children: val(u) + added(u) + c * K = K.
Hint 3
Watch out for deep skew trees: valid inputs for K > 0 are strict single paths, so recursion could hit stack overflow limit.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Mathematical Analysis & Structural Constraints
Let $c(u) \in {0, 1, 2}$ be the number of children of node $u$, and $v(u) \ge 0$ be its initial weight. Let $a(u) \ge 0$ be the non-negative weight added to node $u$.
Because every subtree must evaluate to sum $K$, every child of $u$ must root a subtree whose total sum is $K$. Consequently, the total sum of the subtree at $u$ after additions is:
$$\text{SubtreeSum}(u) = v(u) + a(u) + c(u) \cdot K$$
Setting this equal to $K$ yields:
$$v(u) + a(u) + c(u) \cdot K = K \implies a(u) = K - c(u) \cdot K - v(u)$$
Since $a(u)$ must be non-negative ($a(u) \ge 0$), we analyze by child count $c(u)$:
- Leaf ($c(u) = 0$): $a(u) = K - v(u) \ge 0 \implies v(u) \le K$.
- Single Child ($c(u) = 1$): $a(u) = -v(u) \ge 0$. Since $v(u) \ge 0$, this implies $v(u) = 0$ and $a(u) = 0$.
- Two Children ($c(u) = 2$): $a(u) = -K - v(u) \ge 0$. Since $K \ge 0$ and $v(u) \ge 0$, this requires $K = 0$ and $v(u) = 0$.
Key Structural Deductions
- If $K > 0$: Any node with 2 children makes target $K$ impossible. Furthermore, every non-leaf node must have $v(u) = 0$. The tree must be a linear path ending at a leaf with $v(\text{leaf}) \le K$.
- If $K = 0$: Every node in the tree must initially have $v(u) = 0$, and no weight can be added.
Bottom-Up Traversal Approach
We process the tree in post-order (bottom-up):
- Evaluate left and right subtrees. Both must end up with a total sum of $K$.
- At node $u$, compute the current total sum $S = v(u) + \sum \text{child_sums}$.
- If $S > K$, it is impossible because we can only add non-negative weights; return
-1. - Otherwise, we add $a(u) = K - S$ to the total additions counter and return $K$ to $u$'s parent.
Because valid trees for $K > 0$ can be deep single paths up to $N = 10^5$ nodes, recursive implementations will cause stack overflows in standard Python settings. An iterative post-order traversal using an explicit stack guarantees safe $O(1)$ stack frame overhead per node level.
Python Source Code
from typing import Optional
class TreeNode:
def __init__(self, val: int = 0, left: 'Optional[TreeNode]' = None, right: 'Optional[TreeNode]' = None):
self.val = val
self.left = left
self.right = right
def min_additions_to_balance(root: Optional[TreeNode], K: int) -> int:
"""
Computes the minimum non-negative additions needed to make every
subtree sum equal to K. Returns -1 if impossible.
"""
if root is None:
return 0
total_added = 0
# Explicit stack for post-order traversal: (node, visited_children_flag)
stack = [(root, False)]
# Stores the balanced subtree sums returned from children
child_results = []
while stack:
node, visited = stack.pop()
if not visited:
stack.append((node, True))
if node.right:
stack.append((node.right, False))
if node.left:
stack.append((node.left, False))
else:
num_children = (1 if node.left else 0) + (1 if node.right else 0)
# Start with node's own value and accumulate fixed child subtree sums
current_sum = node.val
for _ in range(num_children):
current_sum += child_results.pop()
# If current sum exceeds K, we cannot reduce it
if current_sum > K:
return -1
total_added += (K - current_sum)
# The subtree rooted at 'node' now equals K
child_results.append(K)
return total_added
Complexity Analysis
- Time Complexity: $\mathcal{O}(N)$, where $N$ is the number of nodes in the binary tree. Each node is pushed to and popped from the stack a constant number of times.
- Space Complexity: $\mathcal{O}(H)$, where $H$ is the height of the tree. The call stack holds at most $\mathcal{O}(H)$ elements. For valid solvable cases with $K > 0$, $H = N$, but memory footprint remains well within execution limits as no recursion frame limit is hit.
Edge Cases to Handle
- Empty Tree (
root is None): Requires 0 additions; returns 0. - Single-node Tree: Returns $K - v(\text{root})$ if $v(\text{root}) \le K$, otherwise
-1. - $K = 0$: Returns 0 if all node values are 0, otherwise
-1. - Node with 2 children when $K > 0$: Handled gracefully by returning
-1as $S = v(u) + 2K > K$.