思路很简单 dfs 然后检查是否有一条路径返回找到了就ok. 代码如下:
1 2 3 4 5 6 7 8 9
| class Solution: def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: if root is None: return False if root.left is None and root.right is None and targetSum - root.val == 0: return True return self.hasPathSum(root.left, targetSum - root.val) or \ self.hasPathSum(root.right, targetSum - root.val)
|