112. 路径总和
题目描述
解题思路
1、前序遍历得到左右子树是否满足条件
2、如果当前叶子和target差值为0,返回True,否则返回False
代码实现
# 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: TreeNode, targetSum: int) -> bool:
"""
1. 前序遍历得到左右子树是否满足条件
2. 如果当前叶子和target差值为0,返回True,否则返回False
"""
if not root:
return False
diff = targetSum - root.val
if diff == 0 and not root.left and not root.right:
return True
left = self.hasPathSum(root.left, diff)
right = self.hasPathSum(root.right, diff)
return left or right