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 Tree INPUT Binary Tree Structure 3 3 coins 0 0 coins 0 0 coins root = [3, 0, 0] n = 3 nodes, n = 3 coins ALGORITHM STEPS 1 DFS Post-order Process children first 2 Calculate Balance balance = coins - 1 3 Count Moves moves += |balance| 4 Return Balance Pass excess to parent Balance Calculation Left: 0-1 = -1 needs 1 Right: 0-1 = -1 needs 1 Root: 3-1+(-1)+(-1)=0 Total: |−1| + |−1| = 2 FINAL RESULT Coins Distributed Evenly 1 1 1 Move 1 Move 2 Output 2 Minimum moves: 2 OK - All nodes have 1 coin Key Insight: The balance at each node represents coins that must flow through the edge to its parent. A positive balance means excess coins flow up; negative means coins must flow down. Total moves = sum of |balance| for all edges, as each unit of imbalance requires one move. TutorialsPoint - Distribute Coins in Binary Tree | DFS with Balance Calculation
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