KatInterview

Minimum Additions to Equalize Every Subtree Sum

Trees & GraphsModel answer
MediumModel answerTrees & Graphstrees-graphspost-ordergreedy

Last 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.