C++ solution using Preorder - O(N)


  • 0
    unordered_map<int,int> umap;
    int maximum = 0;
    void preorder(TreeNode *root)
    {
        if(!root)
            return;
        if(umap.find(root->val) == umap.end())
            umap[root->val] = 0;
        else
        {
            umap[root->val]++;
            maximum = max(maximum,umap[root->val]);
        }
         
        preorder(root->left);
        preorder(root->right);
    }
    vector<int> findMode(TreeNode* root) {
        
        umap.clear();
        maximum = 0;
        vector<int> ans;
        if(!root)
            return ans;
        preorder(root);
       
        for(auto itr = umap.begin();itr != umap.end();itr++)
            if(itr->second == maximum)
                ans.push_back(itr->first);
        
        return ans;
        
    }
    

    };


Log in to reply
 

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