Leetcode 501. Find Mode in Binary Search Tree

 

 

这道题考察计算众数,我们先对每个数字进行一轮计数,放在m中,然后遍历m,将熟知一样的众数追加到m2的vector中,最后把m2的最后指针所指向的vector返回即可

/**
 * 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:
    map<int, int> m;
    vector<int> findMode(TreeNode* root) {
        if(!root) return vector<int>{};
        cnt(root);
        map<int, vector<int>> m2;
        for(auto x: m) m2[x.second].push_back(x.first);
        return (--m2.end())->second;
    }
    void cnt(TreeNode* root) {
        if(!root) return;
        m[root->val]++;
        cnt(root->left);
        cnt(root->right);
    }
};

 

posted @ 2020-02-07 06:40  SteveYu  阅读(118)  评论(0编辑  收藏  举报