Distribute Coins In Binary Tree Problem
Description
LeetCode Problem 979.
You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.
Return the minimum number of moves required to make every node have exactly one coin.
Example 1:
Input: root = [3,0,0]
Output: 2
Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.
Example 2:
Input: root = [0,3,0]
Output: 3
Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.
Example 3:
Input: root = [1,0,2]
Output: 2
Example 4:
Input: root = [1,0,0,null,3]
Output: 4
Constraints:
- The number of nodes in the tree is n.
- 1 <= n <= 100
- 0 <= Node.val <= n
- The sum of all Node.val is n.
Solution
Approach: Post-Order DFS Counting Coins per Edge
Think about edges instead of coins. Cut the edge between a node and its parent: the subtree below has some number of coins and some number of nodes. If it has 3 extra coins, exactly 3 coins must cross that edge upward, and if it is 2 coins short, 2 must cross downward. Moves on different edges cannot replace each other, so the minimum total is the sum, over all edges, of how many coins must cross each one.
Define excess(node) = (coins in the subtree) − (nodes in the subtree). It can be negative. Compute it bottom-up:
left = excess(node.left)andright = excess(node.right)(an empty child gives0).- Add
|left| + |right|to the move count: those coins cross the two child edges. - Return
node.val + left + right - 1, since the node keeps one coin for itself.
The absolute value is the step people get wrong: a subtree that needs coins (negative excess) costs moves just like one that has spare coins.
The root's own excess is 0 because the tree holds exactly n coins, so there is no edge above it to count.
Example with root = [0,3,0]: the left child has excess 3 - 1 = 2 and the right child 0 - 1 = -1, so the answer is |2| + |-1| = 3.
Complexity: O(n) time and O(h) space for the recursion, where n is the number of nodes and h is the height of the tree.
class Solution:
def distributeCoins(self, root: Optional[TreeNode]) -> int:
moves = 0
def excess(node: Optional[TreeNode]) -> int:
"""Coins in node's subtree minus nodes in it: how many coins must cross the edge to the parent."""
nonlocal moves
if node is None:
return 0
left = excess(node.left)
right = excess(node.right)
moves += abs(left) + abs(right) # each coin crossing a child edge, in either direction, is one move
return node.val + left + right - 1 # keep one coin here
excess(root)
return moves
Now write it from memory
Close the write-up and solve it yourself against the tests.