501. 二叉搜索树中的众数(各种常用的偏冷:HashMap的遍历,list和数组的转换)

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

假定 BST 有如下定义:

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

   1
    \
     2
    /
   2
返回[2].

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

进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
class Solution {
    HashMap<Integer,Integer> map = new HashMap();
    int max = Integer.MIN_VALUE;
    public void dfs(TreeNode root){
        if(root != null){
            if(map.containsKey(root.val)){
                if(max <= map.get(root.val))
                    max = map.get(root.val)+1;
                map.put(root.val,map.get(root.val)+1);                
            }
            else{
                if(max < 1)//注意这里,我把这个忘了
                    max = 1;
                map.put(root.val,1);
            }
            dfs(root.left);
            dfs(root.right);
        }
    }
    public int[] findMode(TreeNode root) {
        dfs(root);
        ArrayList<Integer> list =new ArrayList();
        Set<Map.Entry<Integer,Integer>> set = map.entrySet();
        for(Map.Entry<Integer,Integer> entry : set){
            if(entry.getValue() == max)
                list.add(entry.getKey());
        }
        int[] res = new int[list.size()];
        for(int i=0;i<list.size();i++){
            res[i] = list.get(i);
        }
        return res;
    }
}

if(max < 1)//注意这里,我把这个忘了
max = 1;
比如当只有一个节点的时候,直接报错,返回空。

别忘了前提是二叉搜索树呀,肯定用中序遍历,这样肯定是逐渐递增的。不过结果是一样的。

猜你喜欢

转载自blog.csdn.net/xuchonghao/article/details/80774205