Distribute Coins in Binary Tree - Problem

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.

Input & Output

Example 1 — Basic Imbalanced Tree
$ Input: root = [3,0,0]
Output: 2
💡 Note: Root has 3 coins, both children have 0. Move 1 coin from root to each child: root→left (1 move), root→right (1 move). Total: 2 moves.
Example 2 — Already Balanced
$ Input: root = [1,1,1]
Output: 0
💡 Note: Each node already has exactly 1 coin. No moves needed.
Example 3 — Complex Distribution
$ Input: root = [1,0,2]
Output: 2
💡 Note: Left child needs 1 coin, right child has 1 extra. Move 1 coin from right to root (1 move), then from root to left (1 move). Total: 2 moves.

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.

Visualization

Tap to expand
Distribute Coins in Binary TreeInput300Coins: [3, 0, 0]Processexcess+1need-1need-11 move1 moveFlow calculationOutput111Balanced: [1, 1, 1]Answer: 2 moves
Understanding the Visualization
1
Input Tree
Binary tree with uneven coin distribution
2
Calculate Flows
Determine coin excess/deficit for each subtree
3
Count Moves
Sum absolute coin flows through edges
Key Takeaway
🎯 Key Insight: The minimum moves equals the sum of absolute coin excess flowing through each tree edge during redistribution.
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
156.0K Views
Medium Frequency
~25 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen