112. 路径总和 - 力扣(LeetCode)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:if not root:return False# 如果是叶子节点,检查是否满足 targetSumif not root.left and not root.right:return root.val == targetSum# 递归检查左右子树targetSum -= root.valreturn self.hasPathSum(root.left, targetSum) or self.hasPathSum(root.right, targetSum)