目录
一、题目
给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)。
假定 BST 有如下定义:
- 结点左子树中所含结点的值小于等于当前结点的值
- 结点右子树中所含结点的值大于等于当前结点的值
- 左子树和右子树都是二叉搜索树
二、示例
例如:
给定 BST [1,null,2,2],1
\
2
/
2
返回[2].
提示:如果众数超过1个,不需考虑输出顺序
进阶:你可以不使用额外的空间吗?(假设由递归产生的隐式调用栈的开销不被计算在内)
三、思路
1、中序遍历+有序数组的众数
2、遍历(先序,中序,后序均可)+dict字典
3、中序遍历
now记录上一个结点,now[0]为结点的val值,now[1]为该val值出现的次数;
max_val记录当前出现次数最大的值与次数,max_val[0]为次数最大值的val值,max_val[1]为次数最大值的次数;
四、代码
1、
# 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):
# 中序遍历 + 有序数组求众数
res = []
def InTraverse(root):
if root.left:
InTraverse(root.left)
res.append(root.val)
if root.right:
InTraverse(root.right)
if root:
InTraverse(root)
# print(res)
ans = []
count = 0
max_count = 0
last = None
# if len(res) == 0:
# return []
for num in res:
if last == num:
count += 1
else:
count = 1
if count > max_count:
ans = [num]
max_count = count
elif count == max_count:
ans.append(num)
last = num
return ans
if __name__ == '__main__':
# root = TreeNode(1)
# root.right = TreeNode(2)
# root.right.left = TreeNode(2)
# root.right.right = TreeNode(2)
root = TreeNode(1)
root.left = TreeNode(1)
root.right = TreeNode(2)
s = Solution()
ans = s.findMode(root)
print(ans)
2、
# 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):
if root is None:
return []
dict = {}
res = []
def DFS(root):
if root is None:
return
if root.val not in dict:
dict[root.val] = 1
else:
dict[root.val] += 1
DFS(root.left)
DFS(root.right)
DFS(root)
# print(dict)
max_val = max(dict.values())
# print(max_val)
for item, val in dict.items():
if val == max_val:
res.append(item)
return res
if __name__ == '__main__':
# root = TreeNode(1)
# root.right = TreeNode(2)
# root.right.left = TreeNode(2)
# root.right.right = TreeNode(2)
root = TreeNode(1)
root.left = TreeNode(1)
root.right = TreeNode(2)
s = Solution()
ans = s.findMode(root)
print(ans)
3、
# 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):
now = [0, 0]
max_val = [0, 0]
res = []
def InTraverse(root):
nonlocal now, max_val, res
if root.left:
InTraverse(root.left)
if root.val == now[0]:
now[1] += 1
else:
now[0] = root.val
now[1] = 1
if now[1] > max_val[1]:
max_val[1] = now[1]
max_val[0] = now[0]
res = [max_val[0]]
elif now[1] == max_val[1]:
res.append(now[0])
if root.right:
InTraverse(root.right)
if root:
InTraverse(root)
return res
if __name__ == '__main__':
# root = TreeNode(1)
# root.right = TreeNode(2)
# root.right.left = TreeNode(2)
# root.right.right = TreeNode(2)
root = TreeNode(1)
root.left = TreeNode(1)
root.right = TreeNode(2)
s = Solution()
ans = s.findMode(root)
print(ans)