Distribute Coins in Binary Tree (LeetCode 979): Solution and Explanation
A tree with n nodes holds n coins spread unevenly. Moving one coin across one edge is a move. Return the fewest moves that leave exactly one coin on every node.
Intuition
Simulating the moves directly is messy, because coins may need to travel up and then down again. Look at one edge instead.
Cut the edge above some node. The subtree below has a fixed number of nodes and a fixed number of coins. If it has 3 extra coins, those 3 must cross the edge going up. If it is short 2 coins, 2 must cross coming down. No order of moves can avoid that.
These amounts are also enough: each edge carries exactly what it must, and nothing more. So the answer is the sum, over every edge, of |coins in the subtree below - nodes in the subtree below|.
Approach: Post-order excess
- Define
excess(node)as coins minus nodes in the subtree ofnode. For null it is 0. - Compute
left = excess(node.left)andright = excess(node.right)first. - The left edge carries
|left|coins and the right edge carries|right|, so add both tomoves. - Return
node.val + left + right - 1: the node keeps one coin and passes the rest up (or asks for what is missing). - Call it on the root and return
moves. The root's own excess is always 0.
Step-by-step example
root = [3,0,0]
- Left leaf holds 0 coins: excess = 0 - 1 = -1. It needs one coin.
- Right leaf holds 0 coins: excess = -1 as well.
- Root: each edge must carry one coin down, so moves = |-1| + |-1| = 2.
- Root excess = 3 - 1 - 1 - 1 = 0, as expected. The answer is 2.
Code: Python, Java, C++
1class Solution:
2 def distributeCoins(self, root: Optional[TreeNode]) -> int:
3 self.moves = 0
4 def excess(node):
5 if not node:
6 return 0
7 left = excess(node.left)
8 right = excess(node.right)
9 self.moves += abs(left) + abs(right)
10 return node.val + left + right - 1
11 excess(root)
12 return self.moves1class Solution {
2 private int moves;
3 public int distributeCoins(TreeNode root) {
4 moves = 0;
5 excess(root);
6 return moves;
7 }
8 private int excess(TreeNode node) {
9 if (node == null) return 0;
10 int left = excess(node.left);
11 int right = excess(node.right);
12 moves += Math.abs(left) + Math.abs(right);
13 return node.val + left + right - 1;
14 }
15}1class Solution {
2public:
3 int distributeCoins(TreeNode* root) {
4 moves = 0;
5 excess(root);
6 return moves;
7 }
8private:
9 int moves = 0;
10 int excess(TreeNode* node) {
11 if (!node) return 0;
12 int left = excess(node->left);
13 int right = excess(node->right);
14 moves += abs(left) + abs(right);
15 return node->val + left + right - 1;
16 }
17};Time and space complexity
O(n)
Each node is visited once with constant work.
O(h)
The recursion depth is the height of the tree, up to n for a chain.
Other approaches
Subtree counts in two passes (time O(n), space O(n))
First compute nodes and coins per subtree in one traversal, then sum |coins - nodes| over all non-root nodes. Same answer with more bookkeeping.
Greedy simulation (time O(n^2) or worse, space O(n))
Repeatedly move a coin from a rich node toward a poor one. Hard to make optimal and much slower.
Common mistakes
- Only counting coins that move up. A negative excess means coins move down, and those moves count too, so take the absolute value.
- Returning the subtree's coin count instead of coins minus nodes. The edge only carries the difference.
- Adding the root's own excess to the answer. The root has no parent edge, and its excess is 0 anyway.
Frequently asked questions
Why is |excess| per edge a lower bound?
Every coin entering or leaving a subtree must cross the single edge connecting it to the rest of the tree, and the subtree ends with exactly as many coins as nodes.
Why is it also achievable?
Process subtrees bottom-up: each child pushes its surplus up or receives its shortfall, and no edge is ever used in both directions.
Can a node hold a negative number of coins along the way?
In the math, yes: a negative excess is a debt passed to the parent. In real moves the parent sends coins down after it receives them from elsewhere, so the count is the same.