501. 二叉搜索树中的众数

248 篇文章 2 订阅
232 篇文章 0 订阅

一、题目描述

在这里插入图片描述

二、解题

中序遍历

这题先使用中序遍历,将数据变成有序的,然后查找众数,这题的区别众数可以是多个,与之前的169题不一样的是这个题的众数的数量是大于N/2的,可以使用摩尔投票法。所以这题也提供了一个思路如何在数组中查找众数。


class Solution {
    List<Integer> answer = new ArrayList<Integer>();
    int base, count, maxCount;
    public int[] findMode(TreeNode root) {
       //这里不需要使用哈希表 很占空间
       dfs(root);
       //对一个列表进行查找,找一个众数
       int[] res = new int[answer.size()];
       for(int i = 0;i<answer.size();i++){
           res[i] = answer.get(i);
       }
       return res;
    }
    // 中序遍历
     public void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        update(root.val);
        dfs(root.right);
    }
    //更新数据
    public void update(int x) {
        if (x == base) {
            ++count;
        } else {
            count = 1;
            base = x;
        }
        if (count == maxCount) {
            answer.add(base);
        }
        if (count > maxCount) {
            maxCount = count;
            answer.clear();
            answer.add(base);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值