501. 二叉搜索树中的众数
知识点:二叉树、递归
时间:2020年9月24日
题目链接:https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/
题目
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
示例1
输入:
给定 BST [1,null,2,2],
1
\
2
/
2
输出:
[2]
提示:
如果众数超过1个,不需考虑输出顺序
进阶:
你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
解法
- 最简单的想法就是把这个树都遍历了,用map统计节点value频率,用vector排个序,最后得出前面高频的元素。
- 但是没有很好运用题目给的条件——BST,如果把这颗树中序遍历,得到的就是有序的数组,所以在中序遍历的中间处理节点
- 我们需要保存上一个节点的值,
- 如果为空,表示这个是第一个节点
- 比较上一个节点和该节点,相同个数+1
- 不同 个数为1
- 更新节点
- 当现在的个数等于之前的最大值,放入数组
- 当现在的个数大于最大值,把答案数组中的数都清除,放入新的值,更新最大值
代码
#include <stdio.h>
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/*
class Solution {
public:
unordered_map<int,int> m;
vector<int> ans;
bool static cmp(const pair<int,int> x,const pair<int,int> y){
return x.second>y.second;
}
void traversal(TreeNode* root){
if(root==nullptr)return;
m[root->val]++;
traversal(root->left);
traversal(root->right);
return ;
}
vector<int> findMode(TreeNode* root) {
if(root==nullptr) return ans;
traversal(root);
vector<pair<int,int>> tmp(m.begin(),m.end());
sort(tmp.begin(), tmp.end(), cmp);
ans.push_back(tmp[0].first);
for(int i=1;i<tmp.size();i++){
if(tmp[i].second == tmp[0].second)
ans.push_back(tmp[i].first);
else
break;
}
return ans;
}
};*/
class Solution {
public:
int maxcount = 0;
int nowcount = 0;
TreeNode* pre;
vector<int> ans;
bool static cmp(const pair<int,int> x,const pair<int,int> y){
return x.second>y.second;
}
void traversal(TreeNode* root){
if(root==nullptr)return;
traversal(root->left);
if(pre ==nullptr)
nowcount = 1;
else if(root->val == pre->val){
nowcount++;
else
nowcount = 1;
pre = root;
if(nowcount == maxcount){
ans.push_back(root->val);
}else if(nowcount > maxcount){
ans.clear();
ans.push_back(root->val);
maxcount = nowcount;
}
traversal(root->right);
return ;
}
vector<int> findMode(TreeNode* root) {
traversal(root);
return ans;
}
};
int main()
{
TreeNode node1(1);TreeNode node2(3); node1.left = &node2;
TreeNode node3(5);TreeNode node4(5); node2.right= &node3;node3.right = &node4;
Solution s;
vector<int> ans = s.findMode(&node1);
for(int i:ans)
cout<<i<<endl;
return 0;
}
今天也是爱zz的一天哦!