[leetcode] problem 979 – distribute coins in binary tree

Given the root of a binary tree with N nodes, each node in the tree has node.val coins, and there are N coins total.

In one move, we may choose two adjacent nodes and move one coin from one node to another. (The move may be from parent to child, or from child to parent.)

Return the number of moves required to make every node have exactly one coin.

Example

No.1

VKb9lq.png

Input: [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.

No.2

VKbGAe.png

Input: [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.

No.3

VKbYhd.png

Input: [1,0,2]

Output: 2

No.4

VKbN9A.png

Input: [1,0,0,null,3]

Output: 4

Note

  1. 1<= N <= 100
  2. 0 <= node.val <= N

Code

1
2
3
4
5
6
public class  {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private int result = 0;

public int distributeCoins(TreeNode root) {
dfs(root);
return result;
}

private int dfs(TreeNode root) {
if (root == null)
return 0;

int left = dfs(root.left);
int right = dfs(root.right);

result += Math.abs(left) + Math.abs(right);

return left + right + root.val - 1;
}