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 N nodes where 0 <= N <= 10^5, and its height may be as large as N (a single unbranched chain).
  • 0 <= node.val <= 10^6 for every node in the tree.
  • -10^6 <= K <= 10^6 (any negative K on a non-empty tree returns -1).

Step-by-step walkthrough

  1. Restate the problem and input/output contract

    Given the root of a binary tree where each node starts with node.val >= 0 stones and an integer target K, we want every subtree in the tree to end up with a stone sum equal to K. (A subtree rooted at node u consists of u itself 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 -1 if no valid assignment exists (0 for an empty tree None).

    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   = 5
    

    Keep one crucial constraint in mind: the tree can contain up to 10^5 nodes, and an unbranched chain of 10^5 nodes is 10^5 levels 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 = right
    
  2. Why brute force and naive original-sum formulas fail

    Two tempting first attempts fail for completely different reasons:

    1. Exhaustive search (too slow): Trying 0..K extra stones on each of N nodes checks (K + 1)^N combinations. Even for N = 20 and K = 3, 4^20 exceeds a trillion assignments. (We still use this on tiny 5-node trees in unit tests to cross-check our math!)
    2. Adding K - original_subtree_sum independently 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 than K.
  3. 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 c non-null children of node u (c is 0, 1, or 2 in a binary tree) already satisfy the rule so every child subtree sums to K. Right before we place extra stones directly onto u, u's subtree sum is:

    post_children_sum(u) = u.val + (sum of all c child subtrees)
                         = u.val + c * K
    

    To bring u's own subtree sum to K, the extra stones added(u) placed directly on u must 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) <= K must hold at every node! Check what that forces for each child count c:

    • Leaf (c = 0): post_children_sum = u.val. Valid iff u.val <= K; we must add K - u.val stones so the leaf holds K.
    • One child (c = 1): post_children_sum = u.val + K. Valid iff u.val + K <= K (forcing u.val == 0 when K >= 0); we add 0 stones.
    • Two children (c = 2): post_children_sum = u.val + 2 * K. Valid iff u.val + 2 * K <= K, which with non-negative stone counts only holds when K == 0 and u.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.

  4. 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 <= 1 everywhere), and a valid chain of N = 10^5 nodes makes 10^5 nested calls—crashing Python with RecursionError!

    Look closely at post_children_sum = node.val + K * num_children: it depends only on node.val, K, and how many children node has! Whether we inspect node before or after its children, node fails (post_children_sum > K) under the exact same condition, and when every node passes, summing K - post_children_sum across 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 kids
    

    At each iteration we pop one node, compute post_children_sum = node.val + K * len(kids), return -1 immediately if post_children_sum > K, add K - post_children_sum to total_added, and push kids onto stack. Because at most one sibling waits at each level of the active root-to-leaf path, stack holds at most H + 1 nodes (O(H) memory, and just 1 node on a chain!).

  5. 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 has post_children_sum = node.val + 0 * len(kids) = node.val. Because all three nodes hold 0, every node adds 0 and the function returns 0 (whereas even a single stone anywhere makes post_children_sum >= 1 > 0 and returns -1).

  6. 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), where N is the number of nodes in the tree. In the worst case we push and pop each of the N nodes at most once on stack, doing O(1) work per node (inspecting left and right, one multiplication, one comparison, and one addition), and returning early as soon as any node exceeds K.
  • Space: O(H), where H is the height of the tree (the number of edges on the longest root-to-leaf path). At any moment during the iterative DFS, stack holds at most one unvisited sibling per ancestor level along the active path plus the newly pushed children—at most H + 1 nodes in a binary tree (and just 1 node at a time on a single chain of 10^5 nodes).

Edge cases

  • Single-node tree (c = 0): Returns K - root.val when root.val <= K, or -1 when root.val > K.
  • K = 0: The only non-negative target where a node with 2 children can succeed (0 + 2 * 0 <= 0). Returns 0 if every node in the tree already has 0 stones, and -1 if even one stone exists anywhere.
  • Branching node when K > 0: Any node with 2 children has post_children_sum = node.val + 2 * K >= 2K > K, so the function returns -1 as soon as it visits that branching node.
  • Inner node with val > 0 when K > 0: A 1-child node already has node.val + K > K, returning -1.
  • Skewed chain of 10^5 nodes: Handled cleanly in O(1) stack space by the explicit while stack: loop without touching sys.setrecursionlimit.
  • Empty tree (root is None) or K < 0: Returns 0 for None (vacuously satisfied) and -1 for K < 0 on a non-empty tree.

Common mistakes

  • Adding K - S_initial using original subtree sums. Ignoring the extra stones placed on children produces answers that leave ancestor subtrees far heavier than K.
  • Overlooking why branching nodes fail when K > 0. Once two child subtrees each reach K, their parent's subtree already contains at least 2K > K stones before counting parent.val.
  • Using recursion without considering N = 10^5 skewed trees. Unlike balanced binary trees (H ≈ 17), a valid K > 0 tree must be a chain (H = N - 1), which guarantees RecursionError in default Python if solved recursively.
  • Forgetting the K = 0 case. Assuming "any node with 2 children is always -1" fails when K = 0 and all node values are 0.
  • Propagating -1 carelessly in recursive DFS. Adding a child's -1 return value into total_added instead of immediately returning -1 corrupts the sum.

Alternative approaches

  • Direct structural check: Because K = 0 requires every node to hold 0 stones, and K > 0 requires every non-leaf to have 1 child and 0 stones while the unique leaf holds val <= K, you can also verify that exact path structure and return K - leaf.val (or 0 for all-zero K = 0). Our post_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 c children is still algebraically forced to end at target_val = K * (1 - c) so that target_val + c * K = K. If you may only remove non-negative stones (node.val >= target_val), a leaf needs node.val >= K (removing node.val - K), a 1-child node removes all node.val stones to reach 0, and a 2-child node still requires target_val = -K >= 0, which means K = 0 (unless nodes are allowed to hold negative debt). If you can both add and remove stones while keeping final node counts >= 0, feasibility requires K = 0 or c <= 1 everywhere, 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 -1 whenever post_children_sum > K and adding K - post_children_sum otherwise (so any node with c >= 2 children is valid only when K = 0). One subtlety for space complexity: pushing all c children of a wide star node (10^5 children under one root when K = 0) onto stack at once would use O(N) memory instead of O(H). Pushing (node, next_child_index) cursor pairs and advancing one child at a time keeps memory strictly O(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 and O(H) auxiliary memory without recursion! Each node is pushed and popped once with O(1) arithmetic, and on a binary tree stack holds at most one waiting sibling per level along the current root-to-leaf path (<= H + 1 nodes total, and only 1 node on a chain). Because every balanced child subtree is guaranteed to sum to K, we never need an O(N) hash map of subtree sums either.

Follow-up questions

Similar questions

More Reinforce Labs interview questions

All 2 Reinforce Labs questions →