Minimum Added Stones for Equal Subtree Sums
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Problem Statement
Each node of a binary tree stores a non-negative integer val indicating how many stones currently rest on that node:
class TreeNode:
def __init__(
self,
val: int = 0,
left: Optional["TreeNode"] = None,
right: Optional["TreeNode"] = None,
) -> None:
self.val = val
self.left = left
self.right = right
For any node u in the tree, the subtree sum of u is u.val plus the values of all descendants of u. We want every node in the tree to end up with a subtree sum equal to a given integer K.
You are only allowed to place additional stones (>= 0) onto existing nodes; removing stones is forbidden. Implement:
def min_added_stones(root: Optional[TreeNode], K: int) -> int:
Return the smallest total number of extra stones required across the whole tree so that every node's subtree sum equals K. If root is None, return 0. If no non-negative stone placement can satisfy every subtree simultaneously, return -1.
Examples
Example 1
Input:
0
/
0
\
3
K = 8
Output: 5
Explanation: Adding 5 stones to the bottom leaf raises its value from 3 to 8, giving that leaf a subtree sum of 8. Its parent (val = 0) now has subtree sum 0 + 8 = 8, and the root (val = 0) also has subtree sum 0 + 8 = 8 with zero additional stones placed on either ancestor.
Example 2
Input:
2
/ \
1 4
K = 5
Output: -1
Explanation: Bringing the left leaf (1) and right leaf (4) up to subtree sum 5 requires adding 4 and 1 stones respectively. Once both children have subtree sum 5, the root's subtree sum is already 2 + 5 + 5 = 12, which exceeds K = 5. Because stones cannot be taken away, no valid configuration exists.
Example 3
Input:
0
/ \
0 0
K = 0
Output: 0
Explanation: Every subtree already totals 0, so 0 extra stones are needed.
Constraints
- The tree contains
Nnodes where0 <= N <= 10^5, and its height may be as large asN(a single unbranched chain). 0 <= node.val <= 10^6for every node in the tree.-10^6 <= K <= 10^6(any negativeKon a non-empty tree returns-1).
Step-by-step walkthrough
Restate the problem and input/output contract
Given the
rootof a binary tree where each node starts withnode.val >= 0stones and an integer targetK, we want every subtree in the tree to end up with a stone sum equal toK. (A subtree rooted at nodeuconsists ofuitself plus all of its descendants.) We may place any non-negative integer count of extra stones onto any node—never removing stones—and must return the minimum total stones added, or-1if no valid assignment exists (0for an empty treeNone).Example 1: chain 0 -> 0 -> 3, K = 8 Example 2: [2, 1, 4], K = 5 (0) <-- subtree = 0 + 8 = 8 (2) <-- subtree = 2 + 5 + 5 = 12! / / \ (12 > 5: impossible!) (0) <-- subtree = 0 + 8 = 8 (1) (4) \ +4 +1 (3) +5 <-- leaf becomes 8 = 5 = 5Keep one crucial constraint in mind: the tree can contain up to
10^5nodes, and an unbranched chain of10^5nodes is10^5levels deep—well beyond Python's default 1,000-frame recursion limit.from typing import List, Optional class TreeNode: """A binary tree node; val is the number of stones at this node.""" def __init__(self, val: int = 0, left: Optional["TreeNode"] = None, right: Optional["TreeNode"] = None) -> None: self.val = val self.left = left self.right = rightWhy brute force and naive original-sum formulas fail
Two tempting first attempts fail for completely different reasons:
- Exhaustive search (too slow): Trying
0..Kextra stones on each ofNnodes checks(K + 1)^Ncombinations. Even forN = 20andK = 3,4^20exceeds a trillion assignments. (We still use this on tiny 5-node trees in unit tests to cross-check our math!) - Adding
K - original_subtree_sumindependently at every node (wrong math): Stones placed on a child also sit inside every ancestor's subtree. Computing initial subtree sums without accounting for upward ripple leaves ancestor subtrees far heavier thanK.
- Exhaustive search (too slow): Trying
Key insight: bottom-up algebra forces every node's final value
Think from the leaves upward (post-order traversal, where every child is finished before its parent) because placing stones on a parent raises its own subtree sum and its ancestors' sums without altering any child subtree underneath it.
Suppose all
cnon-null children of nodeu(cis0,1, or2in a binary tree) already satisfy the rule so every child subtree sums toK. Right before we place extra stones directly ontou,u's subtree sum is:post_children_sum(u) = u.val + (sum of all c child subtrees) = u.val + c * KTo bring
u's own subtree sum toK, the extra stonesadded(u)placed directly onumust satisfy:post_children_sum(u) + added(u) = K added(u) = K - (u.val + c * K)Because
added(u)must be>= 0(stones cannot be removed),post_children_sum(u) <= Kmust hold at every node! Check what that forces for each child countc:- Leaf (
c = 0):post_children_sum = u.val. Valid iffu.val <= K; we must addK - u.valstones so the leaf holdsK. - One child (
c = 1):post_children_sum = u.val + K. Valid iffu.val + K <= K(forcingu.val == 0whenK >= 0); we add0stones. - Two children (
c = 2):post_children_sum = u.val + 2 * K. Valid iffu.val + 2 * K <= K, which with non-negative stone counts only holds whenK == 0andu.val == 0!
Notice something remarkable: there is no branching choice to optimize. Every node's final stone count
K * (1 - c)is uniquely determined, so whenever a valid assignment exists, it is unique and automatically minimizes the total added stones.- Leaf (
Start from recursive post-order, then eliminate recursion
Writing the bottom-up check recursively expresses the algebra directly:
def min_added_stones_recursive(node: Optional[TreeNode], K: int) -> int: if node is None: return 0 if K < 0: return -1 total_added = 0 num_children = 0 for child in (node.left, node.right): if child is not None: child_added = min_added_stones_recursive(child, K) if child_added == -1: return -1 total_added += child_added num_children += 1 post_children_sum = node.val + K * num_children if post_children_sum > K: return -1 return total_added + (K - post_children_sum)Why not stop here? Because for
K > 0, the only trees that succeed are unbranched chains (c <= 1everywhere), and a valid chain ofN = 10^5nodes makes10^5nested calls—crashing Python withRecursionError!Look closely at
post_children_sum = node.val + K * num_children: it depends only onnode.val,K, and how many childrennodehas! Whether we inspectnodebefore or after its children,nodefails (post_children_sum > K) under the exact same condition, and when every node passes, summingK - post_children_sumacross all nodes gives the same answer in any traversal order.So we replace recursion with an iterative depth-first search (DFS) using an explicit Python list
stack:def children_of(node: TreeNode) -> List[TreeNode]: """Return a list of the 0, 1, or 2 non-null children of node.""" kids: List[TreeNode] = [] if node.left is not None: kids.append(node.left) if node.right is not None: kids.append(node.right) return kidsAt each iteration we pop one
node, computepost_children_sum = node.val + K * len(kids), return-1immediately ifpost_children_sum > K, addK - post_children_sumtototal_added, and pushkidsontostack. Because at most one sibling waits at each level of the active root-to-leaf path,stackholds at mostH + 1nodes (O(H)memory, and just1node on a chain!).Trace the three sample cases
Trace 1 — Valid chain (
0 -> 0 -> 3,K = 8):Step Popped node len(kids) post_children_sum Added here total_added ---- --------------- --------- ------------------ ----------- ----------- 1 root (val=0) 1 0 + 8 * 1 = 8 8 - 8 = 0 0 2 middle (val=0) 1 0 + 8 * 1 = 8 8 - 8 = 0 0 3 leaf (val=3) 0 3 + 8 * 0 = 3 8 - 3 = 5 5 Stack empty -> return 5. Final tree is 0 -> 0 -> 8; subtree sums from bottom to top are 8, 0+8=8, 0+8=8.Trace 2 — Branching tree (
[2, 1, 4], K = 5):Pop root (val=2, 2 children): post_children_sum = 2 + 5 * 2 = 12 > 5 --> return -1 immediately!Trace 3 — Zero target (
[0, 0, 0], K = 0): Every node haspost_children_sum = node.val + 0 * len(kids) = node.val. Because all three nodes hold0, every node adds0and the function returns0(whereas even a single stone anywhere makespost_children_sum >= 1 > 0and returns-1).Complete solution
from typing import List, Optional class TreeNode: """A binary tree node; val is the number of stones at this node.""" def __init__(self, val: int = 0, left: Optional["TreeNode"] = None, right: Optional["TreeNode"] = None) -> None: self.val = val self.left = left self.right = right def children_of(node: TreeNode) -> List[TreeNode]: """Return a list of the 0, 1, or 2 non-null children of node.""" kids: List[TreeNode] = [] if node.left is not None: kids.append(node.left) if node.right is not None: kids.append(node.right) return kids def min_added_stones(root: Optional[TreeNode], K: int) -> int: """Minimum total stones to add so that every subtree sums to exactly K, or -1.""" if root is None: return 0 # Stones are non-negative and we can only add stones, so no subtree can sum to K < 0 if K < 0: return -1 total_added = 0 # stack: explicit DFS stack of TreeNode objects waiting to be checked (at most H + 1 nodes) stack: List[TreeNode] = [root] while stack: node = stack.pop() kids = children_of(node) # Every valid child subtree must end with sum == K, so once children are balanced, # this node's subtree already holds node.val + K * len(kids) before adding to node post_children_sum = node.val + K * len(kids) # Because we cannot remove stones, exceeding K at any node makes balancing impossible if post_children_sum > K: return -1 # Top up this node with the exact deficit needed to bring its subtree sum to K total_added += K - post_children_sum for child in kids: stack.append(child) return total_added✅ Submit now — all tests should pass.
Intuition & how it works
Imagine hanging scale baskets in a tree where each basket's hook supports the stones sitting inside that basket plus all baskets hanging underneath it, and you want every hook in the entire tree to read K grams by only adding stones. Start at the bottom: a leaf basket has nothing hanging underneath it, so it must end up holding K grams. Now step up to its parent: each child hook below already pulls down with K grams! If a parent has c children (c is 0, 1, or 2), the children alone already contribute c * K grams to the parent's hook, leaving room for K - (node.val + c * K) added stones at the parent itself. Whenever node.val + c * K > K, the parent's hook is already too heavy, and since stones cannot be removed, the task is impossible (-1).
Two naive approaches fail quickly here. First, computing each node's initial subtree sum S and summing K - S across nodes ignores upward propagation—stones placed on a leaf also weigh down its parent, grandparent, and root. Second, writing a plain recursive post-order traversal (a tree walk that visits children before their parent using function calls on the call stack, Python's internal memory of active function calls) crashes with RecursionError on a 100,000-node chain—which is the exact shape where K > 0 actually has a valid answer! Because every valid child subtree always contributes K, each node's check node.val + c * K <= K depends only on the node and its child count c, letting an iterative depth-first search (DFS) (a traversal using an explicit stack list) run safely at any depth.
Walk through two sample trees to see the formula in action:
- Single chain 0 -> 0 -> 3 with K = 8: Root (val = 0, 1 child) has 0 + 8 = 8 (adds 0); middle node (val = 0, 1 child) has 0 + 8 = 8 (adds 0); leaf (val = 3, 0 children) has 3 + 0 = 3 (adds 8 - 3 = 5). Total stones added: 5.
- Branching tree [2, 1, 4] with K = 5: Pop the root (val = 2, 2 children). Once both leaves reach 5, the root's subtree already holds 2 + 2 * 5 = 12 > 5, so we immediately return -1.
Complexity
- Time:
O(N), whereNis the number of nodes in the tree. In the worst case we push and pop each of theNnodes at most once onstack, doingO(1)work per node (inspectingleftandright, one multiplication, one comparison, and one addition), and returning early as soon as any node exceedsK. - Space:
O(H), whereHis the height of the tree (the number of edges on the longest root-to-leaf path). At any moment during the iterative DFS,stackholds at most one unvisited sibling per ancestor level along the active path plus the newly pushed children—at mostH + 1nodes in a binary tree (and just1node at a time on a single chain of10^5nodes).
Edge cases
- Single-node tree (
c = 0): ReturnsK - root.valwhenroot.val <= K, or-1whenroot.val > K. K = 0: The only non-negative target where a node with2children can succeed (0 + 2 * 0 <= 0). Returns0if every node in the tree already has0stones, and-1if even one stone exists anywhere.- Branching node when
K > 0: Any node with2children haspost_children_sum = node.val + 2 * K >= 2K > K, so the function returns-1as soon as it visits that branching node. - Inner node with
val > 0whenK > 0: A1-child node already hasnode.val + K > K, returning-1. - Skewed chain of
10^5nodes: Handled cleanly inO(1)stack space by the explicitwhile stack:loop without touchingsys.setrecursionlimit. - Empty tree (
root is None) orK < 0: Returns0forNone(vacuously satisfied) and-1forK < 0on a non-empty tree.
Common mistakes
- Adding
K - S_initialusing original subtree sums. Ignoring the extra stones placed on children produces answers that leave ancestor subtrees far heavier thanK. - Overlooking why branching nodes fail when
K > 0. Once two child subtrees each reachK, their parent's subtree already contains at least2K > Kstones before countingparent.val. - Using recursion without considering
N = 10^5skewed trees. Unlike balanced binary trees (H ≈ 17), a validK > 0tree must be a chain (H = N - 1), which guaranteesRecursionErrorin default Python if solved recursively. - Forgetting the
K = 0case. Assuming "any node with 2 children is always-1" fails whenK = 0and all node values are0. - Propagating
-1carelessly in recursive DFS. Adding a child's-1return value intototal_addedinstead of immediately returning-1corrupts the sum.
Alternative approaches
- Direct structural check: Because
K = 0requires every node to hold0stones, andK > 0requires every non-leaf to have1child and0stones while the unique leaf holdsval <= K, you can also verify that exact path structure and returnK - leaf.val(or0for all-zeroK = 0). Ourpost_children_sum = node.val + K * len(kids)loop expresses both cases uniformly in a single algebraic rule.
Follow-up questions
- How does the algorithm change if stones can be removed (or both added and removed) rather than only added? Every node with
cchildren is still algebraically forced to end attarget_val = K * (1 - c)so thattarget_val + c * K = K. If you may only remove non-negative stones (node.val >= target_val), a leaf needsnode.val >= K(removingnode.val - K), a1-child node removes allnode.valstones to reach0, and a2-child node still requirestarget_val = -K >= 0, which meansK = 0(unless nodes are allowed to hold negative debt). If you can both add and remove stones while keeping final node counts>= 0, feasibility requiresK = 0orc <= 1everywhere, and the minimum total stone adjustments equals the sum of|node.val - K * (1 - c)|over all nodes. - How would you adapt the method for a general tree where each node can have an arbitrary list of children? The exact same balance equation holds with
c = len(node.children):post_children_sum = node.val + K * c, returning-1wheneverpost_children_sum > Kand addingK - post_children_sumotherwise (so any node withc >= 2children is valid only whenK = 0). One subtlety for space complexity: pushing allcchildren of a wide star node (10^5children under one root whenK = 0) ontostackat once would useO(N)memory instead ofO(H). Pushing(node, next_child_index)cursor pairs and advancing one child at a time keeps memory strictlyO(H)even on wide multi-way trees. - How can you guarantee O(N) runtime and O(H) auxiliary memory without hitting recursion depth limits on skewed trees? Our explicit-stack loop already achieves
O(N)time andO(H)auxiliary memory without recursion! Each node is pushed and popped once withO(1)arithmetic, and on a binary treestackholds at most one waiting sibling per level along the current root-to-leaf path (<= H + 1nodes total, and only1node on a chain). Because every balanced child subtree is guaranteed to sum toK, we never need anO(N)hash map of subtree sums either.
Follow-up questions
- How does the algorithm change if stones can be removed (or both added and removed) rather than only added?
- How would you adapt the method for a general tree where each node can have an arbitrary list of children?
- How can you guarantee O(N) runtime and O(H) auxiliary memory without hitting recursion depth limits on skewed trees?
Similar questions
- Compute Net Product Stock from Inventory Tables
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One