#979
Medium Algorithms Distribute coins in binary tree
Tree Depth-First Search Binary Tree
77.3% acceptance
Feb 27, 2026
6064
249
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.
Solution
Rust
Time O(n)
Space O(n)
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
pub fn distribute_coins(root: Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>) -> i32 {
fn dfs(node: &Option<std::rc::Rc<std::cell::RefCell<TreeNode>>>, moves: &mut i32) -> i32 {
match node {
None => 0,
Some(n) => {
let n = n.borrow();
let l = dfs(&n.left, moves);
let r = dfs(&n.right, moves);
*moves += l.abs() + r.abs();
n.val - 1 + l + r
}
}
}
let mut moves = 0;
dfs(&root, &mut moves);
moves
}
}