给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
结点左子树中所含结点的值小于等于当前结点的值
结点右子树中所含结点的值大于等于当前结点的值
左子树和右子树都是二叉搜索树
例如:
给定 BST [1,null,2,2],
1
\
2
/
2
返回[2].
提示:如果众数超过1个,不需考虑输出顺序
进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-mode-in-binary-search-tree
看到这道题最先该想到的是要利用二叉搜索树的性质,左子树小于根节点,右子树大于根节点,中序遍历能得到一个从小到大排序的序列。
对于该题来说,当历史最大长度和当前最大长度相等的时候(max_num == cur_num)将该节点加入结果集中res.append(node.val),当当前最大长度大于历史最大长度是,则需要将原先的数组清空,再将新的值加入结果集,res = [node.val]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
if not root:
return []
max_num = 0
pre_num = None
cur_max = 0
res = []
def dfs(node):
nonlocal pre_num, max_num, cur_max, res
if node:
dfs(node.left)
if node.val == pre_num:
cur_max += 1
else:
cur_max = 1
if cur_max == max_num:
res.append(node.val)
elif cur_max > max_num:
max_num = cur_max
res = [node.val]
pre_num = node.val
dfs(node.right)
dfs(root)
return res