leetcode-501-Find Mode in Binary Search Tree

本文介绍了一种解决LeetCode上编号为501的题目——二叉搜索树中众数查找的方法。通过一次遍历构建哈希表,并记录每个节点出现的次数,最后再次遍历哈希表找出出现次数最多的元素。

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

问题

题目:[leetcode-501]

思路

常规题。遍历一遍,找出出现次数最大的值。
然后枚举哈希表即可。

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> findMode(TreeNode* root) {
        std::vector<int> ret;
        if(!root)
            return ret;
        std::map<int, int> mapper;
        int max = 0;
        preOrder(root,mapper,max);

        typedef std::map<int, int>::const_iterator const_iter;
        const_iter b = mapper.begin();
        const_iter e = mapper.end();
        while(b != e){
            if(b->second==max)
                ret.push_back(b->first);
            ++b;
        }
        return ret;
    }
private:
    void preOrder(TreeNode* root, std::map<int,int>& mapper, int& max){
        if(!root)
            return ;
        int cnt = ++mapper[root->val];
        max = std::max(max, cnt);
        preOrder(root->left, mapper, max);
        preOrder(root->right, mapper, max);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值