给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findMode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
count=collections.defaultdict(int) #有初始默认值的字典
def dummy(root):
if root:
count[root.val]+=1
dummy(root.left)
dummy(root.right)
dummy(root)
macc=max(count.values())
return [i for i in count if count[i]==macc]
执行用时: 88 ms, 在Find Mode in Binary Search Tree的Python3提交中击败了77.16% 的用户