0
class Solution:
    def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:
        ans = []
        tmp = []
        sum_node = 0
        def dfs(node):
            if not node:
                return
            sum_node += node.val
            tmp.append(node.val)
            if sum_node == targetSum and not node.left and not node.right:
                ans.append(tmp[:])
            dfs(node.left)
            dfs(node.right)
            sum_node -= tmp.pop()
        dfs(root)
        return ans
    

It's my solution of leetcode 113. Why it shows 'UnboundedLocalError: local variable 'sum_node' referenced before assignment'?

Lei You
  • 11

1 Answers1

1

Because sum_node is not a local variable to the dfs() function (and as such, you can't use augmented assignment such as += since there's nothing to read-and-write; attempting to do sum_node = ... would work, but would only affect a local name).

You'll need to add a nonlocal statement to have the inner dfs() function's sum_node name refer to the sum_node name in pathSum().

def dfs(node):
    nonlocal sum_node
    ....
AKX
  • 152,115
  • 15
  • 115
  • 172