首页 > 其他 > 详细

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

时间:2019-03-30 21:05:20      阅读:151      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

方法一:

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

 

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

原文:https://www.cnblogs.com/oldby/p/10628913.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!