classSolution:deffindMode(self, root: Optional[TreeNode])-> List[int]:
freq_map = defaultdict(int)#key:元素,value:int
self.searchTree(root, freq_map)
maxfreq =0
res =[]for value in freq_map.values():
maxfreq =max(maxfreq, value)for key, value in freq_map.items():if value == maxfreq:
res.append(key)return res
defsearchTree(self, node, freq_map):if node isNone:return
self.searchTree(node.left, freq_map)
freq_map[node.val]+=1
self.searchTree(node.right, freq_map)
二叉数最近的公共祖先 (LC 236)
题目思路:
代码实现:
classSolution:deflowestCommonAncestor(self, root:'TreeNode', p:'TreeNode', q:'TreeNode')->'TreeNode':if root isNone:returnNoneif root == p:return p
if root == q:return q
left = self.lowestCommonAncestor(root.left, p, q)# 左
right = self.lowestCommonAncestor(root.right, p, q)# 右# 中if left isNoneand right isNone:returnNoneelif left isnotNoneand right isNone:return left
elif left isNoneand right isnotNone:return right
else:return root