https://leetcode.com/problems/distribute-coins-in-binary-tree/description/
讓金幣均攤到二元樹上每個節點 (每個節點都一個金幣)
因為可能會有新增跟移除 (正負),所以在累加答案時要用絕對值
class Solution
{
public:
int distributeCoins(TreeNode *root)
{
int ans = 0;
dfs(root, ans);
return ans;
}
private:
int dfs(TreeNode *root, int &ans)
{
if (!root)
return 0;
const int l = dfs(root->left, ans);
const int r = dfs(root->right, ans);
ans += abs(l) + abs(r);
return root->val + l + r - 1;
}
};
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up