979. Distribute Coins in Binary Tree
一次過有點意外 不過我也只寫得動medium了==
從leaf node 算盈餘 每多一個或少一個都要移動硬幣
class Solution {
public:
int distributeCoins(TreeNode* root) {
int ans = 0;
dfs(root, ans);
return ans;
}
int dfs(TreeNode* root, int &ans){
if(root == nullptr)
return 0;
int left = dfs(root->left, ans);
int right = dfs(root->right, ans);
ans += abs(left) + abs(right);
return left + right + root->val - 1;
}
};
話說我想開始學rust有人有建議ㄇ