Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.
Move from brute-force thinking to an efficient approach using tree strategy.
You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.
Return the minimum number of moves required to make every node have exactly one coin.
Example 1:
Input: root = [3,0,0] Output: 2 Explanation: From the root of the tree, we move one coin to its left child, and one coin to its right child.
Example 2:
Input: root = [0,3,0] Output: 3 Explanation: From the left child of the root, we move two coins to the root [taking two moves]. Then, we move one coin from the root of the tree to the right child.
Constraints:
n.1 <= n <= 1000 <= Node.val <= nNode.val is n.Problem summary: You are given the root of a binary tree with n nodes where each node in the tree has node.val coins. There are n coins in total throughout the whole tree. In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent. Return the minimum number of moves required to make every node have exactly one coin.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Tree
[3,0,0]
[0,3,0]
sum-of-distances-in-tree)binary-tree-cameras)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #979: Distribute Coins in Binary Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int ans;
public int distributeCoins(TreeNode root) {
dfs(root);
return ans;
}
private int dfs(TreeNode root) {
if (root == null) {
return 0;
}
int left = dfs(root.left);
int right = dfs(root.right);
ans += Math.abs(left) + Math.abs(right);
return left + right + root.val - 1;
}
}
// Accepted solution for LeetCode #979: Distribute Coins in Binary Tree
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func distributeCoins(root *TreeNode) (ans int) {
var dfs func(*TreeNode) int
dfs = func(root *TreeNode) int {
if root == nil {
return 0
}
left, right := dfs(root.Left), dfs(root.Right)
ans += abs(left) + abs(right)
return left + right + root.Val - 1
}
dfs(root)
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #979: Distribute Coins in Binary Tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def distributeCoins(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if root is None:
return 0
left, right = dfs(root.left), dfs(root.right)
nonlocal ans
ans += abs(left) + abs(right)
return left + right + root.val - 1
ans = 0
dfs(root)
return ans
// Accepted solution for LeetCode #979: Distribute Coins in Binary Tree
struct Solution;
use rustgym_util::*;
trait Postorder {
fn postorder(&self, sum: &mut i32) -> i32;
}
impl Postorder for TreeLink {
fn postorder(&self, sum: &mut i32) -> i32 {
if let Some(node) = self {
let val = node.borrow().val;
let left = &node.borrow().left;
let right = &node.borrow().right;
let l = left.postorder(sum);
let r = right.postorder(sum);
let m = val + l + r - 1;
*sum += m.abs();
m
} else {
0
}
}
}
impl Solution {
fn distribute_coins(root: TreeLink) -> i32 {
let mut res = 0;
root.postorder(&mut res);
res
}
}
#[test]
fn test() {
let root = tree!(3, tree!(0), tree!(0));
let res = 2;
assert_eq!(Solution::distribute_coins(root), res);
let root = tree!(0, tree!(3), tree!(0));
let res = 3;
assert_eq!(Solution::distribute_coins(root), res);
let root = tree!(1, tree!(0), tree!(2));
let res = 2;
assert_eq!(Solution::distribute_coins(root), res);
let root = tree!(1, tree!(0, None, tree!(3)), tree!(0));
let res = 4;
assert_eq!(Solution::distribute_coins(root), res);
}
// Accepted solution for LeetCode #979: Distribute Coins in Binary Tree
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function distributeCoins(root: TreeNode | null): number {
let ans = 0;
const dfs = (root: TreeNode | null) => {
if (!root) {
return 0;
}
const left = dfs(root.left);
const right = dfs(root.right);
ans += Math.abs(left) + Math.abs(right);
return left + right + root.val - 1;
};
dfs(root);
return ans;
}
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.