Leetcode 501.二叉搜索树中的众数 Find Mode in Binary Search Tree(Java)

Leetcode 501.二叉搜索树中的众数 Find Mode in Binary Search Tree(Java)

##Tree##

二叉搜索树中的众数

二叉搜索树的中序遍历为有序序列,因此本题转换为在有序序列中寻找众数

  • max记录已经遍历过的数中,出现的最大频次
  • count记录当前遍历的数出现的频次
  • TreeNode pre记录上一个遍历的结点,如果题目没有Integer.MAX_VALUE,也可以将pre声明为int,并初始化为Integer.MAX_VALUE
  • LinkedList<Integer> tres记录当前已经遍历过的数中,众数的结果集合

采用中序遍历二叉树

  • root.val == pre.val,本次遍历结点的值与上一次遍历结点的值相等,该数频次count++,否则出现了新的数,该数频次count置为1
  • count == max,新的众数出现,且该众数出现的频次和结果集中众数出现频次相同,将该众数加入结果集
  • count > max,新的众数出现,且该众数出现的频次大于结果集中众数的频次,将结果集清空,新的众数加入结果集,并且更新max
  • 遍历结束后,pre = root

时间复杂度: O(n)

class Solution {
    int max = 1;
    int count = 1;
    TreeNode pre = null;
    LinkedList<Integer> tres = new LinkedList<>();
    
    public int[] findMode(TreeNode root) {
        dfs(root);
        int[] res = new int[tres.size()];
        for (int i = 0; i < res.length; i ++) res[i] = tres.pollFirst();
        return res;
    }
    
    public void dfs(TreeNode root) {
        if (root == null) return;
        dfs(root.left);
        
        if (pre != null && root.val == pre.val) count++;
        else count = 1;
        if (count == max) tres.offerLast(root.val);
        if (count > max) {
            max = count;
            tres.clear();
            tres.offerLast(root.val);
        }
        pre = root;
        
        dfs(root.right); 
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值