AlgoMaster Logo

Distribute Coins in Binary Tree

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

Intuition:

The problem involves distributing coins in order to reach a state where each node in the binary tree (including the root) holds exactly one coin. If a node has more than one coin, it can give some of them to adjacent nodes. If a node lacks a coin, it can request one from its adjacent nodes.

You'll need to use Depth First Search (DFS) to explore this tree, using the property that you can calculate how many moves you need by considering the number of excess or deficit coins each node must balance with its parent.

  • Each node's "excess" is calculated by the number of coins present minus 1 (since one is needed to stay at the node).
  • This excess or deficit is propagated upwards as you return from recursive DFS calls, making it possible to compute the number of moves required at each step.

Here's how you can implement this:

Code: