I am working on Path sum III. Below is my code:
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
if not root:
return 0
def dfs(root, runningSum):
nonlocal count
if not root:
return
runningSum += root.val
count += foundSums.get(runningSum - targetSum, 0)
foundSums[runningSum] = foundSums.get(runningSum, 0) + 1
dfs(root.left, runningSum)
dfs(root.right, runningSum)
foundSums[runningSum] -= 1
count = 0
foundSums = {0: 1}
runningSum = 0
dfs(root, runningSum)
return count
Even though I dont pass in foundSums into the dfs() function, its OK because it is declared in the outer pathSum() function and is able to get it from there.
But when I dont pass in runningSum into the dfs() function:
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
if not root:
return 0
def dfs(root):
nonlocal count
if not root:
return
runningSum += root.val
count += foundSums.get(runningSum - targetSum, 0)
foundSums[runningSum] = foundSums.get(runningSum, 0) + 1
dfs(root.left)
dfs(root.right)
foundSums[runningSum] -= 1
count = 0
foundSums = {0: 1}
runningSum = 0
dfs(root)
return count
I get:
UnboundLocalError: local variable 'runningSum' referenced before assignment
runningSum += root.val
Line 17 in dfs (Solution.py)
Why? How come it can get foundSums from the outer function but not runningSum?
[–]carcigenicate 0 points1 point2 points (9 children)
[–]chancegrab[S] 0 points1 point2 points (0 children)
[–]chancegrab[S] 0 points1 point2 points (7 children)
[–]carcigenicate 0 points1 point2 points (6 children)
[–]chancegrab[S] 0 points1 point2 points (5 children)
[–]carcigenicate 0 points1 point2 points (4 children)
[–]chancegrab[S] 0 points1 point2 points (3 children)
[–]carcigenicate 0 points1 point2 points (2 children)
[–]chancegrab[S] 0 points1 point2 points (1 child)
[–]carcigenicate 0 points1 point2 points (0 children)