日野弥生:勉強しよう
LeetCode 1448 - 统计二叉树中好节点的数目
发表于2025年04月23日
本题判断节点是否好节点,每次判断都要有上层路径的里所有节点的最大值,所以很自然地想到自顶向下的深度优先搜索。
class Solution:
def goodNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
count = 0
# 把最大值向下传递
def goodNodesIMPL(root: Optional[TreeNode], maximum: int):
nonlocal count
if not root:
return
if root.val >= maximum:
count += 1
maximum = max(maximum, root.val)
goodNodesIMPL(root.left, maximum)
goodNodesIMPL(root.right, maximum)
goodNodesIMPL(root, float('-inf'))
return count