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.

For example:

Given the below binary tree and sum = 22,

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \    / \
7    2  5   1

Return:

[
   [5,4,11,2],
   [5,8,4,5]
]

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