https://leetcode.com/problems/find-mode-in-binary-search-tree/

Source


    vector<int> findMode(TreeNode* root) {

        inorder(root);

        vector<ii> viiModes;
        auto it = begin(m_hashMap);
        for (;it != end(m_hashMap); it++) {
            viiModes.push_back(ii(-it->second, it->first));
        }

        sort(begin(viiModes), end(viiModes));

        vector<int> viAns;
        int max = 0;
        for (ii iiMode: viiModes) {
            if (0 == max) {
                viAns.push_back(iiMode.second);
                max = -iiMode.first;
            } else {
                if (-iiMode.first == max) {
                    viAns.push_back(iiMode.second);
                    continue;
                }
                break;
            }
        }

        return viAns;
    }

    void inorder(TreeNode* root) {
        if (nullptr == root) return;

        inorder(root->left);

        const int val = root->val;
        //*/
        m_hashMap[val]++;   // It works!
        /*/
        auto itFound = m_hashMap.find(val);
        if (end(m_hashMap) != itFound) {
            itFound->second++;
        } else {
            m_hashMap.insert(make_pair(val, 0));
        }
        //*/

        inorder(root->right);
    }

GitHub