Distribute Coins in Binary Tree (LeetCode 979): Solution and Explanation

Medium
Tree
Depth First Search
Binary Tree

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

  1. Define excess(node) as coins minus nodes in the subtree of node. For null it is 0.
  2. Compute left = excess(node.left) and right = excess(node.right) first.
  3. The left edge carries |left| coins and the right edge carries |right|, so add both to moves.
  4. Return node.val + left + right - 1: the node keeps one coin and passes the rest up (or asks for what is missing).
  5. Call it on the root and return moves. The root's own excess is always 0.

Step-by-step example

root = [3,0,0]
  1. Left leaf holds 0 coins: excess = 0 - 1 = -1. It needs one coin.
  2. Right leaf holds 0 coins: excess = -1 as well.
  3. Root: each edge must carry one coin down, so moves = |-1| + |-1| = 2.
  4. 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.moves
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each node is visited once with constant work.

Space

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.