1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
class Solution { int ans;
public int distributeCoins(TreeNode root) { dfs(root); return ans; }
private int[] dfs(TreeNode node) { if (node == null) return new int[]{0, 0}; int[] left = dfs(node.left); int[] right = dfs(node.right); int coins = left[0] + right[0] + node.val; int nodes = left[1] + right[1] + 1; ans += Math.abs(coins - nodes); return new int[]{coins, nodes}; } }
|