LEETCODE 979 Distribute Coins in Binary Tree

**Algs

  1. This is a kind of Tree problem, so obviously, we can use a dfs to solve;
  2. 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;
  3. cut the problem into two sub problem; (1) fill each node with one coin; (2) calculate the steps;
  4. 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;
    }
  1. calculate the steps; each node moves one step is one move;
  2. 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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值