Problem Description
Given the root of a binary tree where each node holds a certain number of coins and the total number of coins equals the number of nodes, the goal is to perform moves (each move transfers one coin between adjacent nodes) such that every node ends up with exactly one coin. Determine the minimum number of moves required.
Key Insights
- Each node’s balance is defined as (number of coins at the node) - 1, which indicates the surplus (if positive) or deficit (if negative).
- Use a Depth-First Search (DFS) traversal (post-order) to process children before handling the parent.
- At each node, the number of moves required is the sum of the absolute balances from its left and right subtrees.
- The DFS returns the net balance for each subtree so that these balances can be accumulated at the parent.
- The total moves required is the sum of the absolute values of the surplus/deficits transferred across each edge.
Space and Time Complexity
Time Complexity: O(n) since each node is processed once. Space Complexity: O(h), where h is the height of the tree (due to recursion stack).
Solution
We solve the problem by performing a post-order DFS traversal on the tree. At every node, compute the net coin balance (node.val + left balance + right balance - 1). The moves needed at that node are the absolute values of the left and right balances, reflecting the coins that must be moved into or out of that subtree. Accumulate these moves during the traversal. Finally, the sum of all moves gives the minimum number of moves required to achieve the desired coin distribution.