[LeetCode]501. Find Mode in Binary Search Tree

本文介绍了解决LeetCode上第501题“二叉搜索树中的众数”问题的一种方法。通过深度优先搜索遍历二叉树,并使用哈希表记录每个节点值的出现频率,进而找出出现频率最高的数值。

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

[LeetCode]501. Find Mode in Binary Search Tree

题目描述

这里写图片描述

思路

遍历,存哈希表
遍历两次哈希表
第一次找出最多出现次数
第二次找出最多出现次数的数

代码

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
using namespace std;

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) {
        unordered_map<int, int> um;
        vector<int> res;
        dfs(root, um);
        int maxCount = 0;
        for (auto p : um)
            maxCount = max(maxCount, p.second);
        for (auto p : um)
            if (p.second == maxCount)
                res.push_back(p.first);

        return res;
    }

    void dfs(TreeNode* root, unordered_map<int, int>& um) {
        if (root == NULL)
            return;
        ++um[root->val];
        dfs(root->left, um);
        dfs(root->right, um);
    }
};

int main() {
    TreeNode* n1 = new TreeNode(1);
    TreeNode* n2 = new TreeNode(2);
    TreeNode* n3 = new TreeNode(2);

    n1->right = n2;
    n2->left = n3;

    vector<int> res;
    Solution s;
    res = s.findMode(n1);

    for (int p : res)
        cout << p << " ";
    cout << endl;

    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值