二叉搜索树中的众数java实现

24 篇文章 0 订阅

二叉搜索树中的众数

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);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值