leetcode-二叉搜索树中的众数

501. 二叉搜索树中的众数

题解:

  1. 首先,我们需要遍历二叉搜索树,将所有节点的值存储在一个列表中。
  2. 然后,我们需要统计列表中每个元素出现的次数,找出出现次数最多的元素。
  3. 最后,我们需要返回出现次数最多的元素。
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
import collections
class Solution:
    def findMode(self, root: Optional[TreeNode]) -> List[int]:
        def inorder(root):
            if not root:
                return []
            return inorder(root.left) + [root.val] + inorder(root.right)
        count = collections.Counter(inorder(root))
        max_count = max(count.values())
        return [num for num, freq in count.items() if freq == max_count]

猜你喜欢

转载自blog.csdn.net/weixin_33631777/article/details/136895835