Distribute Coins in Binary Tree

You are given the `root` of a binary tree with `n` nodes, where each `node` holds `node.val` coins. There are exactly `n` coins in the whole tree. In one move you may pick two adjacent nodes and move one coin from one to the other (parent to child or child to parent). Return the minimum number of moves needed so that every node holds **exactly one** coin.

30:00

Distribute Coins in Binary Tree
medium
Free written solution
Topics
Companies

You are given the root of a binary tree with n nodes, where each node holds node.val coins. There are exactly n coins in the whole tree.

In one move you may pick two adjacent nodes and move one coin from one to the other (parent to child or child to parent).

Return the minimum number of moves needed so that every node holds exactly one coin.

Example 1:
Input: {"root":[3,0,0]}
Output: 2
Constraints:
  • The number of nodes in the tree is n.

  • 1≤n≤1001 \leq n \leq 100

  • 0≤Node.val≤n0 \leq \text{Node.val} \leq n

  • The sum of all Node.val is n.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"root":[3,0,0]}

3 nodes and 3 coins. Each subtree will report its excess: coins it holds minus nodes it has. That many coins must cross the edge above it.

moves

0

edges settled

0 / 2

3had 30had 00had 0
coins pushed up
coins sent down
settled: holds 1
negative: owes coins
more than 1

Numbers inside nodes are the coins held right now (0 of 3 nodes settled). A node that owes coins borrows them from its parent when the parent settles.

Variables
VariableValue
moves0
DepthFunction Call
Stack empty
0/5