一.思路
利用中序遍历得到有序数组,再在数组中求众数。
我觉得重点在如何用有序数组求出众数因为众数可能是多个
用两个数第一个存放众数的次数,第二个存放每一个数出现的次数,两遍遍历,第一遍求出众数出现的次数,第二次找出出现次数和众数一样的数放在数组里返回
二.代码实现
class Solution {
public:
vector<int> findMode(TreeNode* root)
{
vector<int>result;
stack<TreeNode*>stack1;
vector<int>vec;
//中序遍历出有序数组
TreeNode* cur = root;
while(cur != NULL || !stack1.empty())
{
if(cur != NULL)
{
stack1.push(cur);
cur = cur->left;
}
else
{
cur = stack1.top();
stack1.pop();
vec.push_back(cur->val);
cur = cur->right;
}
}
//在有序数组中找众数
if(vec.size() == 1)
{
return vec;
}
int max1 = 0;
int max2 = 1;
for(int i = 0;i < vec.size()-1;++i)
{
if(vec[i] == vec[i+1])
{
max2 += 1;
}
else
{
max2 = 1;
}
if(max2 > max1)
{
max1 = max2;
}
}
max2 = 1;
if(max1 == 1)
{
return vec;
}
for(int i = 0;i < vec.size()-1;++i)
{
if(vec[i] == vec[i+1])
{
max2 += 1;
}
else
{
max2 = 1;
}
if(max2 == max1)
{
result.push_back(vec[i]);
}
}
return result;
}
};
另外注意当众数的次数为一时需要另外考虑,因为循环不全