Path Sum II
Tree DFS
Problem
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Note: A leaf is a node with no children.
Solution
class Solution:
    def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
        currPath = []
        allPaths = []
        self.findPaths(root, sum, currPath, allPaths)
        return allPaths
        
    def findPaths(self, root, pathSum, currentPath, allPaths):
        if root is None:
            return 
        
        currentPath.append(root.val)
        if root.left == None and root.right == None and root.val == pathSum:
            allPaths.append(list(currentPath))
            
        self.findPaths(root.left, pathSum - root.val, currentPath, allPaths)
        self.findPaths(root.right, pathSum - root.val, currentPath, allPaths)
        
        del currentPath[-1]
            Last updated
Was this helpful?