详见:https://leetcode.com/problems/find-mode-in-binary-search-tree/description/
C++:
方法一:
/**
* 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;
int mx=0;
unordered_map<int,int> m;
inorder(root,mx,m);
for(auto &a:m)
{
if(a.second==mx)
{
res.push_back(a.first);
}
}
return res;
}
void inorder(TreeNode* node,int &mx,unordered_map<int,int> &m)
{
if(!node)
{
return;
}
inorder(node->left,mx,m);
mx=max(mx,++m[node->val]);
inorder(node->right,mx,m);
}
};
方法二:
/**
* 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)
{
if (!root)
{
return {};
}
vector<int> res;
TreeNode *p = root, *pre = nullptr;
stack<TreeNode*> s;
int mx = 0, cnt = 1;;
while (!s.empty() || p) {
while (p)
{
s.push(p);
p = p->left;
}
p = s.top();
s.pop();
if (pre)
{
cnt = (p->val == pre->val) ? cnt + 1 : 1;
}
if (cnt >= mx)
{
if (cnt > mx)
{
res.clear();
}
res.push_back(p->val);
mx = cnt;
}
pre = p;
p = p->right;
}
return res;
}
};
参考:http://www.cnblogs.com/grandyang/p/6436150.html