题目链接:
https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/
难度:简单
501. 二叉搜索树中的众数
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],
1
\
2
/
2
返回[2].
提示:如果众数超过1个,不需考虑输出顺序
进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
这是简单题???? 不使用额外的空间 ? 个鬼
我用我淳朴的,简单的思路写了一个垃圾的代码
/**
* 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> vec;
vector<int> res;
vector<int> findMode(TreeNode* root) {
if(root==nullptr){
return res;
}
dfs(root);
int maxnum = 0;
unordered_map<int,int> unmap;
for(int i=0;i<vec.size();++i){
unmap[vec[i]]++;
maxnum=maxnum>unmap[vec[i]]?maxnum:unmap[vec[i]];
}
auto it=unmap.begin();
while(it!=unmap.end()){
if(it->second==maxnum){
res.push_back(it->first);
}
it++;
}
return res;
}
void dfs(TreeNode* root){
if(root->left!=nullptr){
dfs(root->left);
}
vec.push_back(root->val);
if(root->right!=nullptr){
dfs(root->right);
}
}
};
运行时间和空间 极差
还有个更好的方法 记录个坐标 周末和拉下的一道题一块补上 题解