https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],
1
\
2
/
2
返回[2].
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map<Integer,Integer>map=new HashMap<>();
public int[] findMode(TreeNode root) {
if(root==null){
return new int[0];
}
//dfs读取所有节点值出现的次数,存入map中
dfs(root);
//根据map的value值从大到小排序,结果放入list中
List<Map.Entry<Integer,Integer>> list=new ArrayList<>(map.entrySet());
Collections.sort(list,new Comparator<Map.Entry<Integer,Integer>>(){
public int compare(Map.Entry<Integer,Integer> o1,Map.Entry<Integer,Integer> o2){
return o2.getValue()-o1.getValue();
}
});
List<Integer> ans=new ArrayList<>();
ans.add(list.get(0).getKey());
//在list中判断众数(可能出现多个)
for(int i=1;i<list.size();i++){
if(list.get(i).getValue()!=list.get(0).getValue()){
break;
}
else{
ans.add(list.get(i).getKey());
}
}
//将ArrayList转换为[]
int[] res=new int[ans.size()];
for(int i=0;i<res.length;i++){
res[i]=ans.get(i);
}
return res;
}
public void dfs(TreeNode root){
if(root==null){
return;
}
if(map.containsKey(root.val)){
map.put(root.val,map.get(root.val)+1);
}
else{
map.put(root.val,1);
}
dfs(root.left);
dfs(root.right);
}
}