前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T136-二叉搜索树中的众数

【leetcode刷题】T136-二叉搜索树中的众数

作者头像
木又AI帮
发布2019-08-08 16:29:09
3040
发布2019-08-08 16:29:09
举报
文章被收录于专栏:木又AI帮木又AI帮

木又连续日更第92天(92/100)


木又的第136篇leetcode解题报告

二叉树类型第26篇解题报告

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

https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/


【题目】

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

假定 BST 有如下定义:

结点左子树中所含结点的值小于等于当前结点的值 结点右子树中所含结点的值大于等于当前结点的值 左子树和右子树都是二叉搜索树

代码语言:javascript
复制
例如:
给定 BST [1,null,2,2],
   1
    \
     2
    /
   2
返回[2].

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

进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)

【思路】

最简单的想法:递归遍历二叉树,使用字典保存所有值及其出现次数,最后找到字典中最大出现次数及其对应值。

【代码】

python版本

代码语言:javascript
复制
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        self.d = {}
        self.count(root)
        max_val = max(self.d.values())
        return list(map(lambda x: x[0], filter(lambda x: x[1] == max_val, self.d.items())))

    def count(self, node):
        if not node:
            return 
        self.d[node.val] = self.d.get(node.val, 0) + 1
        self.count(node.left)
        self.count(node.right)

C++版本

代码语言:javascript
复制
/**
 * 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) {
        vector<int> res;
        if(!root)
            return res;
        map<int, int> d;
        count(root, d);

        int max_val = d[root->val];
        map<int, int>:: iterator it;
        for(it=d.begin(); it != d.end(); it++){
            if(it->second > max_val){
                max_val = it->second;
                res.erase(res.begin(), res.end());
                res.push_back(it->first);
            }else{
                if(it->second == max_val)
                    res.push_back(it->first);
            }
        }
        return res;
    }

    void count(TreeNode* node, map<int, int>& d){
        if(!node)
            return;
        d[node->val]++;
        count(node->left, d);
        count(node->right, d);
    }
};
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-08-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档