思路:
1、深度优先遍历整个树dfs,每遍历一个节点,sum减去当前节点的val
2、如果到达叶子节点(左右子树均为空),sum为0,则说明该路径满足条件,返回True
3、如果遍历到最后,也每返回True,说明不存在满足条件节点,返回False
# class TreeNode:
class Solution:
def hasPathSum(self , root: TreeNode, sum: int) -> bool:
# dfs
if not root:
return False
return self.dfs(root, sum)
def dfs(self, root, sum):
if not root:
return False
sum -= root.val
if not root.left and not root.right and sum == 0:
return True
return self.dfs(root.left, sum) or self.dfs(root.right, sum)