979. 在二叉树中分配硬币

2020-03-22  本文已影响0人  lazy_ccccat

题目描述

https://leetcode-cn.com/problems/distribute-coins-in-binary-tree/

思路

这个思路我没想出来,喵了一眼答案没喵懂。
呢呢三言两语给我说懂了。

代码

class Solution {
public:
    int cnt = 0;
    int distributeCoins(TreeNode* root) {
        dfs(root);
        return this->cnt;
    }

    int dfs(TreeNode* root) { //算子树的过载量
        if (!root) return 0;
        else if (!root->left && !root->right) {
            return root->val - 1;
        } else {
            int left = dfs(root->left);
            int right = dfs(root->right);
            this->cnt += abs(left) + abs(right);
            return root->val + left + right - 1;
        }
    }
};
上一篇下一篇

猜你喜欢

热点阅读