Distribute Coins in Binary Tree
Medium
Topics
You are given the root of a binary tree with n nodes, where each node holds node.val coins. There are n coins in total.
In one move you may take one coin from a node and pass it to an adjacent node — a parent or a child. Return the minimum number of moves needed to leave exactly one coin on every node.
Example 1
null marks a missing child.Input: root = [3,0,0] Output: 2 Explanation: Pass one coin from the root to each child.
Example 2
Input: root = [0,3,0] Output: 3 Explanation: Move one coin from the left child to the root, then two more across 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
- 1 <= n <= 100
- 0 <= Node.val <= n
- The sum of all Node.val is n.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Think about a single edge rather than the whole tree. Whatever a subtree holds, it must end up holding exactly one coin per node — so the number of coins that have to cross the edge above it is fixed, and equals its surplus or deficit.
That quantity does not depend on any choice: if a subtree has 4 coins across 2 nodes, exactly 2 must move up, and if it has 0 coins across 2 nodes, exactly 2 must come down. The direction differs but the number of moves across that edge is the same, so the total is the sum of the absolute surpluses of every subtree.
Approach
- Walk the tree bottom-up, returning each subtree’s balance: its total coins minus its node count.
- For a node, the balance is its own value minus one, plus the balances of both children.
- Each child’s balance is also the number of coins crossing the edge to it, so add the absolute value of each child’s balance to the answer.
- The root’s balance comes out as 0, which is the guarantee that the totals matched.
Walkthrough
root = [0, 3, 0]
left child val 3 balance 3 - 1 = +2 -> 2 moves on its edge
right child val 0 balance 0 - 1 = -1 -> 1 move on its edge
root val 0 balance 0 - 1 + 2 - 1 = 0
total moves = 2 + 1 = 3Complexity
- Time — O(n): each node is visited once and does constant work.
- Space — O(h): the recursion stack, h being the height of the tree.
Common Pitfalls
- Adding the balance rather than its absolute value cancels a surplus against a deficit and undercounts — coins moving in opposite directions are still moves.
- The balance returned must subtract 1 for the node itself, otherwise every subtree looks richer than it is.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def distributeCoins(self, root):
self.moves = 0
def surplus(node):
if not node:
return 0
left = surplus(node.left)
right = surplus(node.right)
self.moves += abs(left) + abs(right)
return node.val + left + right - 1
surplus(root)
return self.movesimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int distributeCoins(TreeNode root) {
moves = 0;
surplus(root);
return moves;
}
private int moves;
private int surplus(TreeNode node) {
if (node == null) return 0;
int left = surplus(node.left), right = surplus(node.right);
moves += Math.abs(left) + Math.abs(right);
return node.val + left + right - 1;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int distributeCoins(TreeNode* root) {
int moves = 0;
function<int(TreeNode*)> surplus = [&](TreeNode* node) -> int {
if (!node) return 0;
int left = surplus(node->left), right = surplus(node->right);
moves += abs(left) + abs(right);
return node->val + left + right - 1;
};
surplus(root);
return moves;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number}
*/ var distributeCoins = function(root) {
let moves = 0;
const surplus = (node) => {
if (!node) return 0;
const left = surplus(node.left), right = surplus(node.right);
moves += Math.abs(left) + Math.abs(right);
return node.val + left + right - 1;
};
surplus(root);
return moves;
};