【LeetCode】501. Find Mode in Binary Search Tree

本文介绍了一种在含有重复元素的二叉搜索树中查找出现频率最高元素的方法。通过使用HashMap记录每个节点出现次数并找出最大值,再将所有出现次数等于最大值的节点收集到ArrayList中,最后转换为数组返回结果。

题目:

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
Both the left and right subtrees must also be binary search trees.

思路:
写个方法,用map来记录每个数字出现的个数,以及最大值。
然后写个arraylist来保存key,因为可能有俩。
然后再遍历一下存入array

Code:

private Map<Integer,Integer> map =new HashMap<>();
private int max = 0; 
public int[] findMode(TreeNode root) {
  if(root==null)
      return new int[0];
  inOrdroot(root);
    
    List<Integer> b = new ArrayList<>();
   for(int key:map.keySet()){
       if (map.get(key) == max)
			b.add(key);
   }
    int []res = new int[b.size()];
    
    for(int i=0;i<res.length;i++){
        res[i] = b.get(i);
    }
    return res;
    }

private void inOrdroot(TreeNode root){
   if(root.left!=null) 
     inOrdroot(root.left);
    
    map.put(root.val,map.getOrDefault(root.val, 0) + 1);
    max = Math.max(max,map.get(root.val));
    
    if(root.right!=null)
     inOrdroot(root.right);    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值