leetcode二叉树-501. 二叉搜索树中的众数
考点:遍历,然后转化成数组中找众数
package binarytree.findMode;
import binarytree.untils.GenerateTreeNode;
import binarytree.untils.TreeNode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 501. 二叉搜索树中的众数
* 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
*
* 假定 BST 有如下定义:
*
* 结点左子树中所含结点的值小于等于当前结点的值
* 结点右子树中所含结点的值大于等于当前结点的值
* 左子树和右子树都是二叉搜索树
* 例如:
* 给定 BST [1,null,2,2],
*
* 1
* \
* 2
* /
* 2
* 返回[2].
*
* 提示:如果众数超过1个,不需考虑输出顺序
*/
public class findMode {
/**
* 搜索遍历
* @param root
* @return
*/
public static int[] findMode(TreeNode root) {
Map<Integer,Integer> map = new HashMap<>();
inOrder(root,map);
int max = 0;
for (Map.Entry<Integer,Integer> m: map.entrySet()) {
max=Math.max(max,m.getValue());
}
List<Integer> res1 = new ArrayList<>();
int i = 0;
for (Map.Entry<Integer,Integer> m: map.entrySet()) {
if(m.getValue()==max){
res1.add(m.getKey());
}
}
int[] res = new int[res1.size()];
for (int j = 0; j < res1.size(); j++) {
res[j] = res1.get(j);
}
return res;
}
private static void inOrder(TreeNode root,Map<Integer,Integer> map){
if(root == null){
return;
}
if(map.containsKey(root.val)){
int count = map.get(root.val);
map.put(root.val,++count);
}
else{
map.put(root.val,1);
}
inOrder(root.left,map);
inOrder(root.right,map);
}
public static void main(String[] args) {
Integer[] nums = {1,null,2};
TreeNode treeNode = GenerateTreeNode.generateTreeNode(nums);
int[] mode = findMode(treeNode);
for (int i = 0; i < mode.length; i++) {
System.out.println(mode[i]);
}
}
}
不恋尘世浮华,不写红尘纷扰
标签:
leetcode刷题
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
2020-12-17 mysql 1054 看数据库是否开了大小写
2020-12-17 centos7 安装 Mysql 5.7.27,详细完整教程
2019-12-17 20191217-关于JPA @Query查询数据一直为空,直接在数据库里执行SQL则可以查出来