Leet Code Daily - 2024-05-18 - Distribute Coins in Binary Tree
Code
● ● ●c++/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
// count[node] => {tree size, number of coins}
unordered_map<TreeNode*, pair<int, int>> count;
void doCount(TreeNode* root) {
if (root == nullptr) {
count[root] = make_pair(0, 0);
} else {
doCount(root->left);
doCount(root->right);
count[root] = make_pair(1 + count[root->left].first +
count[root->right].first,
root->val + count[root->left].second +
count[root->right].second);
}
}
int doDistribute(TreeNode* root) {
if (root == nullptr) {
return 0;
};
int ret = 0;
if (root->left != nullptr) {
const int diff = count[root->left].second - count[root->left].first;
count[root->left].second -= diff;
count[root].second += diff;
ret += abs(diff) + doDistribute(root->left);
}
if (root->right != nullptr) {
const int diff =
count[root->right].second - count[root->right].first;
count[root->right].second -= diff;
count[root].second += diff;
ret += abs(diff) + doDistribute(root->right);
}
return ret;
}
int distributeCoins(TreeNode* root) {
doCount(root);
return doDistribute(root);
}
};