当前位置:   article > 正文

LeetCode刷题之路:501. 二叉搜索树中的众数_leetcode刷题 二叉搜索树中的众数 js解法

leetcode刷题 二叉搜索树中的众数 js解法

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

假定 BST 有如下定义:

结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],

   1
    \
     2
    /
   2
  • 1
  • 2
  • 3
  • 4
  • 5

返回[2].

提示:如果众数超过1个,不需考虑输出顺序

进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)

#最直观的思路

# 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
class Solution:
    def findMode(self, root: TreeNode) -> List[int]:
        res = []
        pre = float('-inf')
        count = 0
        max_count = 0
        # def mid(root):
        #     nonlocal res, pre, count, max_count
        #     if not root:
        #         return
        #     mid(root.left)
        #     if root.val == pre:
        #         count += 1
        #     else:
        #         count = 1
        #     if count == max_count:
        #         res.append(root.val)
        #     elif count > max_count:
        #         res = [root.val]
        #     max_count = max(max_count, count)
        #     pre = root.val
        #     mid(root.right)
        # mid(root)
        # return res
        stack = []
        while stack or root:
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            if root.val == pre:
                count += 1
            else:
                count = 1
            if count == max_count:
                res.append(root.val)
            elif count > max_count:
                res = [root.val]
            max_count = max(count, max_count)
            pre = root.val
            root = root.right
        return res
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/寸_铁/article/detail/882452?site
推荐阅读
相关标签
  

闽ICP备14008679号