C++ Simple Solution, Concise Code


  • 0

    O(n) space
    O(n) time

    class Solution {
        int dfs(TreeNode* cur, unordered_map<int, int>& mp, int& freq) {
            if (!cur)
                return 0;
            int l = dfs(cur->left, mp, freq), r = dfs(cur->right, mp, freq),
                sum = l + r + cur->val;
            freq = max(++mp[sum], freq);
            return sum;
        }
    public:
        vector<int> findFrequentTreeSum(TreeNode* root) {
            unordered_map<int, int> mp;
            int freq = 0;
            dfs(root, mp, freq);
            vector<int> res;
            for (auto& i : mp) {
                if (i.second == freq)
                    res.push_back(i.first);
            }
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.