917. Distribute Coins in Binary Tree

MediumTreesBinary TreeTree DPDFS

Given the root of a binary tree with n nodes and exactly n coins distributed among them, in one move you may transfer a single coin between adjacent (parent-child) nodes. Return the minimum number of moves needed to make every node hold exactly one coin. The tree is given as a level-order array.

Input: A level-order array of the tree (coin counts).

Output: Integer — the minimum number of moves.

Examples

Example 1
Input: [3,0,0]
Output: 2
Explanation: Move two coins from the root to each child.
Example 2
Input: [0,3,0]
Output: 3
Explanation: Balance coins across the tree.
Example 3
Input: [1,0,2]
Output: 2
Explanation: Two transfers balance the tree.

Constraints

Asked by

AmazonGoogleBloombergMicrosoftMeta
Solve this problem in the editor →