DFS_C++


  • 0
    class Solution {
    public:
    vector<int> findMode(TreeNode* root) {
        unordered_map<int,int> mp;
        int MAX = 0;
        vector<int> res;
        find(root, mp, MAX);
        for(auto num : mp){
            if(num.second == MAX){
                res.push_back(num.first);
            }
        }
        return res;
    }
    
    void find(TreeNode* root, unordered_map<int,int>& mp, int& MAX){
        if(root == nullptr) return;
        if(mp.find(root->val) == mp.end()){mp[root->val] = 0;}
        mp[root->val]++;
        MAX = max(MAX, mp[root->val]);
        find(root->left, mp, MAX);
        find(root->right, mp, MAX);
    }
    };

Log in to reply
 

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