0%

Distribute Coins in Binary Tree

Question

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 1:
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.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
@param: TreeNode
@return: int
Algorithm: divide and conquer
左右子树返回需要的硬币数。用res记录需要移动的步数
*/
int res = 0;
public int distributeCoins(TreeNode root) {
if (root == null) return 0;
dfs(root);
return res;
}

public int dfs(TreeNode root) {
if (root == null) return 0;
int l = dfs(root.left);
int r = dfs(root.right);
res = res + Math.abs(l) + Math.abs(r);
return root.val + l + r - 1;
}