leetcode:501. 二叉搜索树中的众数

题目描述

501. 二叉搜索树中的众数

题目来源

在这里插入图片描述

题目解析

我们都知道二叉搜索树的中序遍历是有序的,有一种方式就是把二叉搜索树中序遍历的结果存放到一个数组中,因为这个数组是升序的(虽然有重复的),我们可以遍历这个数组,这里使用几个变量

使用变量curent表示当前的值,count表示当前值的数量,maxCount表示重复数字最大的数量。list集合存放结果

1,如果节点值等于curent,count就加1,

2,如果节点不等于current,说明遇到了下一个新的值,更新current为新的值,然后让count=1;

接着比较count和maxCount的大小,

  • 如果count==maxCount,就把当前节点的值加入到集合list中(遇到的值一定是个新值)。
  • 如果count>maxCount,先把list集合清空,然后再把当前节点的值加入到集合list中,最后在更新maxCount的值。
private TreeNode pre;
    private int curCount = 0;
    private int maxCount = 0;
    private ArrayList<Integer> list = new ArrayList<Integer>();
    public int[] findMode(TreeNode root) {
        helper(root);
        return list.stream().mapToInt(Integer::intValue).toArray() ;
    }
    
    private void helper(TreeNode root){
        if (root == null){
            return;
        }
        
        helper(root.left);
        
        if (pre == null || pre.val != root.val){
            curCount = 1;
        }else {
            curCount++;
        }
        
        if (curCount == maxCount){
            list.add(root.val);
        }else if (curCount > maxCount){
            maxCount = curCount;
            list.clear();;
            list.add(root.val);
        }
        
        pre = root;
        helper(root.right);
    }

在这里插入图片描述

class Solution {
   
public:
    // 树中节点的数目在范围 [1, 104] 内
    vector<int> findMode(TreeNode* root) {
        helper(root);
        return vec;
    }

private:
    TreeNode* pre;
    vector<int> vec;
    int maxCount, currCount;
private:
    void helper(TreeNode* root){
        if(root == NULL){
            return;
        }

        helper(root->left);

        if(pre == NULL || pre->val != root->val){
            currCount = 1;
        }else{
            currCount++;
        }

        if(currCount == maxCount){
            vec.emplace_back(root->val);
        }else if(currCount > maxCount){
            vec.clear();
            maxCount = currCount;
            vec.emplace_back(root->val);
        }

        pre = root;
        helper(root->right);
    }

};

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值