clean C++ solution


  • 0
    G
    vector<int> findFrequentTreeSum(TreeNode* root) {
        unordered_map<int, int> table;
        helper(root, table);
        
        auto maxCnt = 0;
        vector<int> sol;
        for (auto&& p : table) {
            if (p.second > maxCnt) {
                sol.clear();
                sol.emplace_back(p.first);
                maxCnt = p.second;
            } else if (p.second == maxCnt) {
                sol.emplace_back(p.first);
            }
        }
        
        return sol;
    }
    
    int helper(const TreeNode* root, unordered_map<int, int>& table) {
        if (root == nullptr) {
            return 0;
        }
        
        auto leftSum = helper(root->left, table);
        auto rightSum = helper(root->right, table);
        auto curSum = leftSum + rightSum + root->val;
        if (table.find(curSum) == std::end(table)) {
            table.emplace(curSum, 0);
        }
        table[curSum]++;
        return curSum;
    }

Log in to reply
 

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