Clean C++ 10 lines DFS O(n) time O(n) space


  • 1
        vector<int> findMode(TreeNode* root) {
            vector<int>vec;
            unordered_map<int,int>m;
            DFS(root,m);
            int max=0;
            for(auto x:m)
                if(x.second>max) vec.clear(),vec.push_back(x.first),max=x.second;
                else if(x.second==max) vec.push_back(x.first);
            return vec;
        }
        
        void DFS(TreeNode* root, unordered_map<int,int>& m){
            if(!root) return;
            m[root->val]++,DFS(root->left,m),DFS(root->right,m);
        }
    

Log in to reply
 

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