**Algs :
- This is a kind of Tree problem, so obviously, we can use a dfs to solve;
- for this problem, we want to fill each node with one coin, so we can ask left child if you have any coins left, please give them to me, then doing the same thing to the right child; Thus, its better to use the postOrder dfs;
- cut the problem into two sub problem; (1) fill each node with one coin; (2) calculate the steps;
- its easy to fill each node with one coin, just traverse by postOrder and return the coins each node remains, 0 could be -1, 2 could be 1, then pass it to its root;
private int dfs(TreeNode node) {
if (node == null) return 0;
// postOrder
int l = dfs(node.left);
int r = dfs(node.right);
return l + r + node.val - 1;
}
- calculate the steps; each node moves one step is one move;
- so, whatever the remaining number of coins is negative or positive , its steps are absolute;
class Solution {
private int ans = 0;
public int distributeCoins(TreeNode root) {
dfs(root);
return ans;
}
// dfs to fill each node with 1 coin
private int dfs(TreeNode node) {
if (node == null) return 0;
// postOrder
int l = dfs(node.left);
int r = dfs(node.right);
ans += Math.abs(l) + Math.abs(r);
return l + r + node.val - 1;
}
}