0
点赞
收藏
分享

微信扫一扫

微信小程序4种弹框

自信的姐姐 2024-07-01 阅读 50

给你一个含重复值的二叉搜索树(BST)的根节点 root ,找出并返回 BST 中的所有 众数(即,出现频率最高的元素)。

如果树中有不止一个众数,可以按 任意顺序 返回。

假定 BST 满足如下定义:

  • 结点左子树中所含节点的值 小于等于 当前节点的值
  • 结点右子树中所含节点的值 大于等于 当前节点的值
  • 左子树和右子树都是二叉搜索树
public static int[] findMode(TreeNode root) {
        int[] result;    //记录结果
        List<Integer> list=new ArrayList<>();
        Map<Integer,Integer> map=new HashMap();
        inorder(root,map);

        // 1. 获取 entrySet 并转换为 List
        List<Map.Entry<Integer, Integer>> mapList = new ArrayList<>(map.entrySet());
        // 2. 对 List 进行排序(从到到小)
        mapList.sort((c1, c2) -> c2.getValue().compareTo(c1.getValue()));
        //3. 将频率最高的加入list中
        list.add(mapList.get(0).getKey());
        for(int i=1;i<mapList.size();i++){
            if(mapList.get(i-1).getValue()==mapList.get(i).getValue()){
                list.add(mapList.get(i).getKey());
            }else {
                break;
            }
        }
        //将list转化为数组
        result=list.stream().mapToInt(Integer::intValue).toArray();
        return result;
    }

    public static void inorder(TreeNode root,Map<Integer,Integer> map){
        if(root==null) return;
        inorder(root.left,map);
        map.put(root.val,map.getOrDefault(root.val,0)+1);
        inorder(root.right,map);
    }
举报

相关推荐

0 条评论