Problem 412
Distribute Coins in a Binary Tree
Medium · 20 pts · Tree, Depth-First Search, Binary Tree
Problem
Each node of a binary tree holds some coins (its value), and the total number of coins equals the number of nodes. In one move you can pass a single coin between two adjacent nodes (a parent and its child, in either direction). Find the minimum number of moves needed so that every node ends up with exactly one coin. For each subtree, the coins it has minus the nodes it contains must flow across the edge to its parent, and each coin crossing an edge costs one move.
Input
The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.
Output
Print the minimum number of moves.
Constraints
1 <= number of nodes <= 100; 0 <= value <= number of nodes; the values add up to the number of nodes
Example input
3 3 0 0
Example output
2
Explanation
In the tree 3 / 0 0, the root has two extra coins and each child needs one. One coin moves to the left child and one to the right child: 2 moves.