LeetCode题解之 Find Mode in Binary Search Tree

1、题目描述

2、问题分析

使用map记录元素出现的次数。

3、代码

 1 vector<int> v;
 2     map<int,int> m;
 3     vector<int> findMode(TreeNode* root) {
 4         if (root == NULL)
 5             return v;
 6         preOrder(root);
 7         int n = 0;
 8         for(map<int,int>::iterator it = m.begin(); it != m.end(); it++) {
 9             if (it->second >= n)
10                 n = it->second;
11         }
12         
13         for(map<int, int>::iterator it = m.begin(); it != m.end(); it++) {
14             if (it->second == n)
15                 v.push_back(it->first);
16         }
17         
18         return v;
19     }
20     
21     void preOrder(TreeNode *root)
22     {
23         if (root != NULL)
24             m[root->val]++;
25         else 
26             return;
27         preOrder(root->left);
28         preOrder(root->right);
29     }

猜你喜欢

转载自www.cnblogs.com/wangxiaoyong/p/10460024.html