AlgoMaster Logo

Distribute Coins in Binary Tree

tree=[3, 0, 0]
1class Solution {
2    private int moves;
3
4    public int distributeCoins(TreeNode root) {
5        moves = 0;
6        dfs(root);
7        return moves;
8    }
9
10    private int dfs(TreeNode node) {
11        if (node == null) return 0;
12
13        // Calculate excess from subtrees
14        int leftExcess = dfs(node.left);
15        int rightExcess = dfs(node.right);
16
17        // Calculate moves at this node
18        moves += Math.abs(leftExcess) + Math.abs(rightExcess);
19
20        // Calculate and return excess
21        int excess = node.val + leftExcess + rightExcess - 1;
22        return excess;
23    }
24}
0 / 20
300Total Moves: 0