leetcode題解:二叉搜索樹衆數

/**
 * 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:
    void InOrder(map<int,int>&m,TreeNode*root)
    {
        if(root)
        {
            InOrder(m,root->left);
            if(m.find(root->val)==m.end())//不在map中
            {
              m.insert(pair<int,int>(root->val,1));
            }
            else 
            {
                
                  m[root->val]++;
            }
            InOrder(m,root->right);
        }
    }
    vector<int> findMode(TreeNode* root) 
    {
        map<int,int>m;
        InOrder(m,root);  
        int MAX=0; 
        //找到衆數
        for(auto it=m.begin();it!=m.end();it++)
        {
            if(it->second>=MAX)
            MAX=it->second;
        }
        vector<int>result;
        for(auto it=m.begin();it!=m.end();it++)
        {
            if(it->second==MAX)
            result.push_back(it->first);
        }
        return(result);
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章