Distribute Coins in Binary Tree

Medium

Topics
TreeDFS

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

030
more than one coinno coins
Each node holds the number of coins written in it, and there are exactly as many coins as nodes — 3 of each. Every node must end up with exactly one, and a coin moves only between a node and one directly joined to it, one coin per move. The answer counts those moves.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [3,0,0]
Output: 2
Explanation: Pass one coin from the root to each child.

Example 2

300
more than one coinno coins
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

012
more than one coinno coins
Input:  root = [1,0,2]
Output: 2

Example 4

0310
more than one coinno coins
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

  1. Walk the tree bottom-up, returning each subtree’s balance: its total coins minus its node count.
  2. For a node, the balance is its own value minus one, plus the balances of both children.
  3. 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.
  4. 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 = 3

Complexity

  • 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.moves
SensAI
Beta
Tap the mic to stop voice mode