每日一题~二叉搜索树中的众数

题目链接:501. 二叉搜索树中的众数 - 力扣(LeetCode)

题目描述:

思路分析:

由题可知,题目中所给的树是一颗二叉搜索树,二叉搜索树的中序遍历结果是一个从小到大的数据集,那么我们可以根据这一特性来获取到二叉搜索树中的所有 val,放在一个 List 中,并且这个 List 是有序的。获取到二叉搜索树中的所有 val 之后,我们接下来就可以寻找众数。我们使用 max 来记录 List 中众数出现的次数,使用 Map 来保存 val 及其出现的次数,这样在后面我们就可以直接从 Map 中获取到 val 出现的次数。如果 val 出现的次数等于 max,那么这个数就是一个众数,我们再使用一个 ArrayList 来存放众数,将所有的众数都存放到 ArrayList 之后,我们再将 ArraryList 中的数据拷贝到数组中就可以了。

代码示例:

class Solution {
    public int[] findMode(TreeNode root) {
        List<Integer> list = new LinkedList<>();
        // 中序遍历
        inOrder(root,list);
        // 存放众数
        Map<Integer,Integer> map = new HashMap<>();
        int max = 1;
        for(int i = 0; i < list.size(); i++) {
            int tmp = list.get(i);
            int j = i;
            while(i < list.size() && list.get(i) == tmp) {
                i++;
            }
            Integer cnt = i-j;
            map.put(tmp,cnt);
            max = cnt > max ? cnt : max;
            i--;
        }
        // ans 存放最终结果
        ArrayList<Integer> ans = new ArrayList<>();
        for(int i = 0; i < list.size(); i++) {
            if(map.size() == 0) break;   
            if(map.get(list.get(i)) == null) continue;
            if(map.get(list.get(i)) == max) {
                ans.add(list.get(i));
                map.remove(list.get(i));
            }
                     
        }
        // 将 ans 的数据拷贝回数组中
        int[] res = new int[ans.size()];
        int i = 0;
        for(int x : ans) {
            res[i++] = x;
        }
        return res;
    }
    public void inOrder(TreeNode root,List<Integer> list) {
        if(root == null) return;
        inOrder(root.left,list);
        list.add(root.val);
        inOrder(root.right,list);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值