Find all the elements that appears mostly.
Solution:
Use a hashmap to count the time of duplicates. Then save the elements with the highest appearing time into the output.
Code:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> findMode(TreeNode* root) { vector<int> res; unordered_map<int, int> m; int ct = 0; findM(root, m, ct); for(auto a:m){ if(a.second == ct) res.push_back(a.first); } return res; } private: void findM(TreeNode* root, unordered_map<int, int> &m, int &c){ if(!root) return; c = max(c, ++m[root->val]); findM(root->left, m, c); findM(root->right, m, c); } };
No comments :
Post a Comment