【力扣】501. 二叉搜索树中的众数

给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。

假定 BST 有如下定义:

结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],

1

2
/
2
返回[2].

提示:如果众数超过1个,不需考虑输出顺序

进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-mode-in-binary-search-tree

第一次解答:使用map:

int maxMore = 0; //最大值是哪个
    int maxValCount = 0; //最大值有几个

    public int[] findMode(TreeNode root) {
        Map<Integer,Integer> resultMap = new HashMap<Integer,Integer>();
        dfs(resultMap,root);
        int[] result = new int[maxValCount];
        
        for (Map.Entry<Integer, Integer> entry : resultMap.entrySet()) {
            if(entry.getValue() == maxMore){
                result[--maxValCount] = entry.getKey();
            }
        }
        return result;
    }

    public void dfs(Map<Integer,Integer> resultMap,TreeNode root){
        if(root == null){
            return ;
        }
        int currentVal = resultMap.getOrDefault(root.val,0) + 1;
        resultMap.put(root.val,currentVal);
        if(currentVal > maxMore){
            maxValCount = 1;
            maxMore = currentVal;
        } else if(currentVal == maxMore){
            maxValCount++;
        }
        dfs(resultMap,root.left);
        dfs(resultMap,root.right);
    }

运行时间:4ms、内存消耗:40.8M,时间复杂度:O(1) 空间复杂度:O(n)

一个入行不久的Java开发,越学习越感觉知识太多,自身了解太少,只能不断追寻
原文地址:https://www.cnblogs.com/fengtingxin/p/13726352.html