Path Sum II
113. Path Sum II
Difficulty: Medium
Related Topics: Backtracking, Tree, DFS, Binary Tree
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.
A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: [[5,4,11,2],[5,8,4,5]] Explanation: There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22
Example 2:
Input: root = [1,2,3], targetSum = 5 Output: []
Example 3:
Input: root = [1,2], targetSum = 0 Output: []
First Attempt:
Code:
# 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) -> List[List[int]]:
temp = []
ans = []
sam = 0
dup = root
def dfs(root, targetSum, sam, temp):
if root:
if root.left == None and root.right == None:
if sam != targetSum:
return False
else:
return True
if root.left:
temp.append(root.val)
if dfs(root.left, targetSum, sam+root.left.val, temp):
temp.append(root.left.val)
ans.append(temp.copy())
else:
temp.pop()
if root.right:
temp.append(root.val)
if dfs(root.right, targetSum, sam+root.right.val, temp):
temp.append(root.right.val)
ans.append(temp.copy())
temp=[]
else:
temp.pop()
dfs(dup, targetSum, root.val, temp)
return ans
Second Attempt:
Code:
class Solution:
def pathSum(self, root, targetSum):
result = []
def dfs(root, path):
nonlocal result
if not root:
return []
path += [root.val]
if not root.left and not root.right:
# Adding the condition needed in the question
if sum(path)==targetSum:
result.append(path.copy())
dfs(root.left, path)
dfs(root.right, path)
path.pop()
return result
return dfs(root, [])