This question can be solved by Depth First Search.
We want to find all possible path that sum to the given number. Since the path does not have to start from the root, so any node can be the start of the path. We need to try every node to be the root and find if there is path from that root that sum up to the given number.
# 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 = rightclassSolution:defpathSum(self,root:TreeNode,sum:int)->int:ifnotroot:return0defdfs(root,sum):res=0ifnotroot:returnresifsum==root.val:res+=1res+=dfs(root.left,sum-root.val)res+=dfs(root.right,sum-root.val)returnresreturndfs(root,sum)+self.pathSum(root.left,sum)+self.pathSum(root.right,sum)