The Distribute Coins in Binary Tree coding problem presents a binary tree where each node contains a certain number of coins. The total number of coins in the tree is equal to the total number of nodes. Your goal is to move the coins so that every node has exactly one coin. A "move" consists of moving one coin between two adjacent nodes (parent-child). You need to find the minimum number of moves required to balance the tree.
This "Medium" difficulty problem is a favorite at companies like Google, Meta, and Goldman Sachs. It tests your mastery of Depth-First Search (DFS) and your ability to aggregate information from the bottom up. It evaluations whether you can recognize that the number of moves passing through an edge is determined by the "excess" or "deficit" of coins in the subtree below that edge. It’s a sophisticated test of tree-based logic and greedy optimization.
This problem uses Post-order Traversal (DFS).
node.val + left_balance + right_balance - 1.abs(left_balance) + abs(right_balance).Consider a tree: Root(0) -> Left(3), Right(0).
abs() when summing moves. A deficit of 5 coins requires 5 moves to enter, just as an excess of 5 requires 5 moves to leave.Practice "Bottom-Up" tree problems. Many tree problems require you to return a value to the parent that summarizes the state of the entire subtree. In this case, the balance is the "net flow" of coins needed for that subtree.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sum Root to Leaf Numbers | Medium | Solve | |
| Count Univalue Subtrees | Medium | Solve | |
| Count Nodes Equal to Average of Subtree | Medium | Solve | |
| Path Sum III | Medium | Solve | |
| Binary Tree Pruning | Medium | Solve |