動機

複習dfs

Problem

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

 

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22Output: true

Example 2:

Input: root = [1,2,3], targetSum = 5Output: false

Example 3:

Input: root = [1,2], targetSum = 0Output: false

 

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

Sol

注意到是root到leaf!!

def dfs(r,target,cnt):
    if r is None:
        return False
    elif r.val+cnt == target and not r.left and not r.right:
        return True
    else:
        return dfs(r.left,target,cnt+r.val) or dfs(r.right,target,cnt+r.val)
class Solution:
    def hasPathSum(self, r: TreeNode, targetSum: int) -> bool:
        return dfs(r,targetSum,0)