Skip to main content

Path Sum II

Question

None

Example 1
Input: 
[
[5,4,8],
[11,13,4],
[7,2,1]
]

Target Sum: 22

Output:
[
[5,4,11,2],
[5,8,4,1]
]

Solution

all//Path Sum II.py


# 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, sum):
res = []
self.dfs(root, sum, [], res)
return res

def dfs(self, node, sum, path, res):
if not node:
return
path.append(node.val)
if node.val == sum and not node.left and not node.right:
res.append(path)
self.dfs(node.left, sum - node.val, path[:], res)
self.dfs(node.right, sum - node.val, path[:], res)