当前位置:网站首页>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
边栏推荐
- 【MySQL】索引的分类
- 比较版本号[双指针截取自己想要的字串]
- 指标陷阱:IT领导者易犯的七个KPI错误
- [NOIP2013]积木大赛 [NOIP2018]道路铺设 贪心/差分
- 二叉树的基本操作
- 为什么数字化转型战略必须包括持续测试?
- CIO's discussion and Analysis on the definition of high-performance it team
- Relationship and difference between enterprise architecture and project management
- #yyds干货盘点# 解决名企真题:扭蛋机
- flink sql 命令行 连接 yarn
猜你喜欢

Recent public ancestor offline practice (tarjan)

【MySQL】索引的分类

名单揭晓 | 2021年度中国杰出知识产权服务团队

I received a letter from CTO inviting me to interview machine learning engineer
Design and practice of new generation cloud native database

Pytest collection (2) - pytest operation mode

对象内存布局

Mysql——》索引存储模型推演

Chapter 9 Yunji datacanvas company has been ranked top 3 in China's machine learning platform market

详解LockSupport的使用
随机推荐
快乐数[环类问题之快慢指针]
plantuml介绍与使用
100年仅6款产品获批,疫苗竞争背后的“佐剂”江湖
Fundamentals - IO intensive computing and CPU intensive computing
[monomer] recommended configuration of streaming information i-bpsv3 server
【MySQL】索引的分类
Wechat applet, continuously playing multiple videos. Synthesize the appearance of a video and customize the video progress bar
13th Blue Bridge Cup group B national tournament
IDA动态调试apk
比较版本号[双指针截取自己想要的字串]
Use of vscode
Flume interview questions
MIT|256KB 内存下的设备上训练
辅音和声母的区别?(声母与辅音的区别)
【juc学习之路第9天】屏障衍生工具
RestTemplate 远程调用工具类
Microsoft, Columbia University | Godel: large scale pre training of goal oriented dialogue
TOPS,处理器运算能力单位、每秒钟可进行一万亿次
基于三维GIS的不动产管理应用
Sonic cloud real machine learning summary 6 - 1.4.1 server and agent deployment