Distribute Coins in Binary Tree

Medium · Trees · Tree · Depth-First Search · Binary Tree

Problem

You are given the root of a binary tree with n nodes, where node.val is the number of coins on that node. There are exactly n coins in the whole tree.

In one move you take one coin and carry it across one edge, from a parent to a child or from a child to its parent.

Return the fewest moves that leave every node with exactly one coin.

Examples

Input: root = [0,3,0]
Output: 3

The left child sends one coin up to the root and another through the root to the right child: 1 + 2 = 3 moves.

Input: root = [1,0,0,null,3]
Output: 4

The node holding 3 sends two coins up to its parent (2 moves); one stays and the other goes on through the root to the root's right child (2 more moves).

Constraints

Approaches

Follow-up

What if each node wanted its own number of coins, and nodes could have any number of children? The same edge argument holds with excess = coins - total need for every subtree; see the use case "Any tree, any target per node".

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…