leetcood学习笔记-501- 二叉搜索树中的众数

题目描述:

方法一:

class Solution:
    def findMode(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        dic = {}
        stack = [root]
        while stack:
            node = stack.pop()
            if node.val not in dic:
                dic[node.val] = 0
            dic[node.val] += 1
            if node.left:
                stack.append(node.left)
            if node.right:
                stack.append(node.right)
        re = []
        max_v = max(dic.values())
        for key,val in dic.items():
            if val == max_v:
                re.append(key)
        return re

方法二:

class Solution:
    def findMode(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        cur_val = -10**15
        cur_fre = 0
        ans = []
        fre_max = 0
        def find_fre(p):
            nonlocal cur_val#nonlocal关键字用来在函数或其他作用域中使用外层(非全局)变量
            nonlocal cur_fre
            nonlocal ans
            nonlocal fre_max
            if not p:
                return
            find_fre(p.left)
            if cur_val == p.val:
                cur_fre += 1
            else:
                cur_val = p.val
                cur_fre = 1
            if cur_fre == fre_max:
                ans.append(cur_val)
            if cur_fre > fre_max:
                fre_max = cur_fre
                ans.clear()
                ans.append(cur_val)
            find_fre(p.right)
            
        find_fre(root)
        return ans

 

posted @ 2019-03-30 20:53  oldby  阅读(251)  评论(0编辑  收藏  举报