Distribute Coins in Binary Tree

medium binary tree dfs post-order

Problem

You are given the root of a binary tree with n nodes where each node 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 the other (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.

Inputroot = [3, 0, 0]
Output2
From the root with 3 coins, send one coin to each of its two empty children — 2 moves total.

def distributeCoins(root):
    moves = 0
    def dfs(node):
        nonlocal moves
        if not node:
            return 0
        left = dfs(node.left)
        right = dfs(node.right)
        moves += abs(left) + abs(right)
        return node.val + left + right - 1
    dfs(root)
    return moves
function distributeCoins(root) {
  let moves = 0;
  function dfs(node) {
    if (!node) return 0;
    const left = dfs(node.left);
    const right = dfs(node.right);
    moves += Math.abs(left) + Math.abs(right);
    return node.val + left + right - 1;
  }
  dfs(root);
  return moves;
}
class Solution {
    int moves = 0;
    public int distributeCoins(TreeNode root) {
        dfs(root);
        return moves;
    }
    private int dfs(TreeNode node) {
        if (node == null) return 0;
        int left = dfs(node.left);
        int right = dfs(node.right);
        moves += Math.abs(left) + Math.abs(right);
        return node.val + left + right - 1;
    }
}
class Solution {
public:
    int moves = 0;
    int distributeCoins(TreeNode* root) {
        dfs(root);
        return moves;
    }
    int dfs(TreeNode* node) {
        if (!node) return 0;
        int left = dfs(node->left);
        int right = dfs(node->right);
        moves += abs(left) + abs(right);
        return node->val + left + right - 1;
    }
};
Time: O(n) Space: O(h)