二叉搜索树中的众数(python)

题目描述:

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

假定 BST 有如下定义:

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

例如:

给定BST [1,null,2,2] 返回[2]

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

# 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]
        """
        #思路:使用字典,边遍历树边计数,最后找出众数
        dict_ = {}
        res = []
        
        if root == None:
            return res
        
        def find(node,dict_):
            if node != None:
                if node.val in dict_.keys():
                    dict_[node.val] = dict_[node.val] + 1
                else:
                    dict_[node.val] = 1
                find(node.left,dict_)
                find(node.right,dict_)
                
        find(root,dict_)
        
        max_ = max(dict_.values())
        
        for key,value in dict_.items():
            if value == max_:
                res.append(key)
                
        return res

菜鸟一枚,代码仅供参考,如有问题,望指正~


版权声明:本文为weixin_40510799原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。