当前位置:网站首页>LC501. Mode in binary search tree
LC501. Mode in binary search tree
2022-07-01 22:38:00 【996 Chong Chong】
Violent calculation mode , Spatial complexity O(N), Because an array is used to store the results of the middle order traversal
Then it is the ordered array to find the mode , In fact, this does not use the characteristics of binary search tree .
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) # Count the number of each element with a dictionary
for i in res:
d[i] += 1
x = sorted(d.values())
max = x[-1] # Get the most elements
for i in d.items():
if i[1] == max:
sol.append(i[0]) # Add the corresponding key to the answer
return sol
Spatial complexity O(1) Methods
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) # Using the property that middle order is order , Add processing logic in the middle order
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: # Cannot be empty when equal to , So add this sentence
self.res.append(root.val)
if self.count > self.maxcount: # When it is larger than, it needs to be changed , So you need to empty it and re append
self.maxcount = self.count
self.res = []
self.res.append(root.val)
inorder(root.right)
inorder(root)
return self.res
边栏推荐
猜你喜欢
随机推荐
记录一次spark on yarn 任务报错 Operation category READ is not supported in state standby
LIS (longest ascending subsequence) problem that can be understood [easy to understand]
基准环路增益与相位裕度的测量
2020-ViT ICLR
flink sql 命令行 连接 yarn
小 P 周刊 Vol.11
Wechat open platform scanning code login [easy to understand]
快乐数[环类问题之快慢指针]
详解ThreadLocal
CNN convolution neural network principle explanation + image recognition application (with source code) [easy to understand]
flink sql-client 使用 对照并熟悉官方文档
多种智能指针
Classify boost libraries by function
20220701
The leader of the cloud native theme group of beacon Committee has a long way to go!
Recent public ancestor offline practice (tarjan)
Compensation des créneaux horaires
Is PMP certificate really useful?
RestTemplate 远程调用工具类
Medium pen test questions: flip the string, such as ABCD, print out DCBA








