501. Find Mode in Binary Search Tree

本文介绍两种查找二叉搜索树中最常出现元素的方法。方法一利用HashMap进行节点计数,方法二则采用中序遍历,不使用额外的数据结构。这两种方法分别实现了较高的运行效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

在这里插入图片描述在这里插入图片描述

题目链接

https://leetcode.com/problems/find-mode-in-binary-search-tree/

方法思路

Approach1: based on HashMap

class Solution {
    //Runtime: 6 ms, faster than 51.99%
    //Memory Usage: 40.3 MB, less than 54.73%
    Map<Integer, Integer> map = new HashMap<>();
    public int[] findMode(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        dfs(root);
        int maxVal = -1;
        for (int count : map.values()){
            if (count > maxVal)
                maxVal = count;
        }
        for (Map.Entry<Integer,Integer> e : map.entrySet()){
            if (e.getValue() == maxVal)
                res.add(e.getKey()); 
        }
        int[] ans = new int[res.size()];
        for (int i=0; i<res.size(); i++)
            ans[i] = res.get(i);
        return ans;
    }
    
    private void dfs(TreeNode root){
        if(root == null) return;
        dfs(root.left);
        map.put(root.val, map.getOrDefault(root.val, 0) + 1);
        dfs(root.right);
    }
}

Approach2: without HashMap

public class Solution {
    //Runtime: 1 ms, faster than 99.59%
    //Memory Usage: 39.2 MB, less than 74.32% 
    Integer prev = null;
    int count = 1;
    int max = 0;
    public int[] findMode(TreeNode root) {
        if (root == null) return new int[0];
        
        List<Integer> list = new ArrayList<>();
        traverse(root, list);
        
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); ++i) res[i] = list.get(i);
        return res;
    }
    
    private void traverse(TreeNode root, List<Integer> list) {
        if (root == null) return;
        traverse(root.left, list);
        if (prev != null) {
            if (root.val == prev)
                count++;
            else
                count = 1;
        }
        if (count > max) {
            max = count;
            list.clear();
            list.add(root.val);
        } else if (count == max) {
            list.add(root.val);
        }
        prev = root.val;
        traverse(root.right, list);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值