Balance Tree Coins with the Fewest Adjacent Transfers
Quick Overview
Balance Tree Coins with the Fewest Adjacent Transfers. A binary tree has n nodes and exactly n coins in total; each node stores its current coin count in val.
Balance Tree Coins with the Fewest Adjacent Transfers
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
### Problem
A binary tree has n nodes and exactly n coins in total; each node stores its current coin count in val. One move transfers one coin across one parent-child edge in either direction. Return the minimum moves needed to leave exactly one coin at every node.
```cpp
class Solution {
public:
int distributeCoins(TreeNode* root);
};
```
### Examples
**Example 1:**
```text
Input: root = [1,0,2]
Output: 2
Explanation: Move one coin from the right child to the root, then from the root to the left child.
```
**Example 2:**
```text
Input: root = [0,0,null,3]
Output: 3
Explanation: The bottom left grandchild sends two coins upward to its parent, and that parent sends one to the root.
```
### Constraints
- The tree contains n nodes, with `1 <= n <= 100`.
- `0 <= Node.val <= n`.
- All node values sum to n.
### Contract considerations
Node values represent coin counts, not costs or immutable labels. The reference computes flows without modifying those values.
```hint Read the boundary condition
For one subtree, how many coins must cross its single connection to the parent?
```
### Boundary reminders
Node values represent coin counts, not costs or immutable labels. The reference computes flows without modifying those values.
Overview: Balance Tree Coins with the Fewest Adjacent Transfers. A binary tree has n nodes and exactly n coins in total; each node stores its current coin count in val.
Balance Tree Coins with the Fewest Adjacent Transfers
Google
Jun 22, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0
Problem
A binary tree has n nodes and exactly n coins in total; each node stores its current coin count in val. One move transfers one coin across one parent-child edge in either direction. Return the minimum moves needed to leave exactly one coin at every node.
class Solution {
public:
int distributeCoins(TreeNode* root);
};
Examples
Example 1:
Input: root = [1,0,2]
Output: 2
Explanation: Move one coin from the right child to the root, then from the root to the left child.
Example 2:
Input: root = [0,0,null,3]
Output: 3
Explanation: The bottom left grandchild sends two coins upward to its parent, and that parent sends one to the root.
Constraints
The tree contains n nodes, with
1 <= n <= 100
.
0 <= Node.val <= n
.
All node values sum to n.
Contract considerations
Node values represent coin counts, not costs or immutable labels. The reference computes flows without modifying those values.
Boundary reminders
Node values represent coin counts, not costs or immutable labels. The reference computes flows without modifying those values.