【Leetcode_总结】501. 二叉搜索树中的众数- python

Q:

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

假定 BST 有如下定义:

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

例如:
给定 BST [1,null,2,2],

   1
    \
     2
    /
   2

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

思路:中序遍历二叉搜索树,然后对输出求众数

代码:

# 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 root == None:
            return []
        else:
            res = []
            self.middle_digui(root, res)
        from collections import Counter
        dic = Counter(res)
        max = 0
        for k in dic:
            if dic[k] > max:
                max = dic[k]
        temp = []
        for k in dic:
            if dic[k] == max:
                temp.append(k)
        return temp


    def middle_digui(self,root,res):
        if root == None:
            return
        self.middle_digui(root.left,res)
        res.append(root.val)
        self.middle_digui(root.right,res)

猜你喜欢

转载自blog.csdn.net/maka_uir/article/details/86534794