C++ | Leetcode C++题解之 第508题出现次数最多的子树元素和-题解:

class Solution {
    unordered_map<int, int> cnt;
    int maxCnt = 0;

    int dfs(TreeNode *node) {
        if (node == nullptr) {
            return 0;
        }
        int sum = node->val + dfs(node->left) + dfs(node->right);
        maxCnt = max(maxCnt, ++cnt[sum]);
        return sum;
    }

public:
    vector<int> findFrequentTreeSum(TreeNode *root) {
        dfs(root);
        vector<int> ans;
        for (auto &[s, c]: cnt) {
            if (c == maxCnt) {
                ans.emplace_back(s);
            }
        }
        return ans;
    }
};
上一篇:【南方科技大学】CS315 Computer Security 【Lab6 IoT Security and Wireless Exploitation】


下一篇:Codeforces Round 981 (Div. 3) A-D