力扣题目:501. 二叉搜索树中的众数 - 力扣(LeetCode)
给你一个含重复值的二叉搜索树(BST)的根节点 root
,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。
如果树中有不止一个众数,可以按 任意顺序 返回。
假定 BST 满足如下定义:
- 结点左子树中所含节点的值 小于等于 当前节点的值
- 结点右子树中所含节点的值 大于等于 当前节点的值
- 左子树和右子树都是二叉搜索树
示例 1:
输入:root = [1,null,2,2] 输出:[2]
示例 2:
输入:root = [0] 输出:[0]
提示:
- 树中节点的数目在范围
[1, 10^4]
内 -10^5 <= Node.val <= 10^5
算法如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
//1.递归遍历每一个值,求众数
public int[] findMode(TreeNode root) {
//map存储值
Map<Integer,Integer> map=new HashMap<>();
//调用遍历
findZ(root,map);
//求众数
int max=Integer.MIN_VALUE;
//zui大的出现次数
for(Integer i: map.values())
{
if(i>max)
{
max=i;
}
}
//列表添加总数
List<Integer> list=new ArrayList<>();
for(Map.Entry<Integer,Integer> entry:map.entrySet())
{
if(entry.getValue()==max)
{
list.add(entry.getKey());
}
}
//列表转成数组
int[] a=new int[list.size()];
for(int i=0;i<list.size();i++)
{
a[i]=list.get(i);
}
return a;
}
public void findZ(TreeNode root, Map<Integer,Integer> map)
{
if(root==null)
{
return;
}
//就用中序
findZ(root.left,map);
if(map.containsKey(root.val))
{
map.put(root.val,map.get(root.val)+1);
}else {
map .put(root.val,1);
}
findZ(root.right,map);
}
}