../ Competitive Programming
-rw-r--r--aguang1.9 KiB1 min read

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);
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window