437. Path Sum III

437. Path Sum III

# 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 pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
        self.ans=0
        if root!=None:
            self.dfs1(root,targetSum)

        return self.ans

    def dfs1(self,root,targetSum):
        if root!=None:
            self.dfs(root,targetSum)
            self.dfs1(root.left,targetSum)
            self.dfs1(root.right,targetSum)

    def dfs(self,root,targetSum):
        if root==None:return
        if root.val==targetSum:self.ans+=1
        # includes root
        self.dfs(root.left,targetSum-root.val)
        self.dfs(root.right,targetSum-root.val)

这里dfs一定是包含root.val的情况

你可能感兴趣的:(leetcode)