当前位置:网站首页>LC501. 二叉搜索树中的众数
LC501. 二叉搜索树中的众数
2022-07-01 21:45:00 【996冲冲冲】
暴力计算众数,空间复杂度O(N),因为用了一个数组存储中序遍历的结果
之后就是有序数组求众数了,这其实没有用到二叉搜索树的特性。
class Solution(object):
def findMode(self, root):
""" :type root: TreeNode :rtype: List[int] """
sol = []
res = []
def inorder(root):
if not root:
return
inorder(root.left)
res.append(root.val)
inorder(root.right)
inorder(root)
d = collections.defaultdict(int) #用一个字典统计各个元素的数量
for i in res:
d[i] += 1
x = sorted(d.values())
max = x[-1] #获取最多的那个元素
for i in d.items():
if i[1] == max:
sol.append(i[0]) #将对应的键加入答案
return sol
空间复杂度O(1)的方法
def findMode(self, root):
""" :type root: TreeNode :rtype: List[int] """
self.count = 0
self.maxcount = 0
self.res = []
self.pre = None
def inorder(root):
if not root:
return
inorder(root.left) #利用中序是有序的性质,在中序位置加入处理逻辑
if self.pre == None:
self.count = 1
elif root.val == self.pre.val:
self.count += 1
else:
self.count = 1
self.pre = root
if self.count == self.maxcount: #等于的时候不能置空,所以要加上这一句
self.res.append(root.val)
if self.count > self.maxcount: #大于的时候就需要换,所以需要置空并且重新append
self.maxcount = self.count
self.res = []
self.res.append(root.val)
inorder(root.right)
inorder(root)
return self.res
边栏推荐
- Go — 相关依赖对应的exe
- List announced | outstanding intellectual property service team in China in 2021
- Sonic cloud real machine learning summary 6 - 1.4.1 server and agent deployment
- [monomer] recommended configuration of streaming information i-bpsv3 server
- Internet of things RFID, etc
- Count the number of each character in the character
- flink sql 命令行 连接 yarn
- 【生态伙伴】鲲鹏系统工程师培训
- Several ways of writing main function in C
- Chapter 9 Yunji datacanvas company has been ranked top 3 in China's machine learning platform market
猜你喜欢
随机推荐
The leader of the cloud native theme group of beacon Committee has a long way to go!
Significance and measures of security encryption of industrial control equipment
灵动微 MM32 多路ADC-DMA配置
使用闭包实现点击按钮切换 toggle
Copy ‘XXXX‘ to effectively final temp variable
Little p weekly Vol.11
Several ways of writing main function in C
按照功能对Boost库进行分类
Matlab traverses images, string arrays and other basic operations
小 P 周刊 Vol.11
高攀不起的希尔排序,直接插入排序
keras训练的H5模型转tflite
13th Blue Bridge Cup group B national tournament
【juc学习之路第8天】Condition
QT 使用FFmpeg4将argb的Qimage转换成YUV422P
CSDN购买的课程从哪里可以进入
Unity 使用Sqlite
Go — 相关依赖对应的exe
Flume interview questions
[NOIP2013]积木大赛 [NOIP2018]道路铺设 贪心/差分









