I am leetcoding, when doing recursion, I used to define an internal function which does the recursion job and some variables in the outer function. like this:
def recur(root):
res = []
def bt(node):
# specific recursive job in this function
# and modify outer res
bt(root)
return res
This writing style always works but today when I want to define a variable out the inside function like this:
class Solution:
@staticmethod
def is_balanced(root):
fla = True
def post_tr_verify(node):
if not node or not fla:
return 0
left = post_tr_verify(node.left)
right = post_tr_verify(node.right)
if abs(left - right) > 1:
fla = False
return 0
return max(left, right) + 1
post_tr_verify(root)
return fla
it reminds me 'UnboundLocalError: local variable 'fla' referenced before assignment'
, I fixed it by add one sentence inside the post_tr_verify
function: nonlocal fla
.
But I still can't figure out why my writing style doesn't work this time.
Why this error comes?
My previous writing recursion example:
class Solution:
@staticmethod
def permute(nums):
cur, res = [], []
print(id(res))
def bt(li):
if li and len(li) == len(nums):
res.append(cur[:])
print(id(res))
return
for ele in nums:
if not li:
cur.append(ele)
bt(cur)
cur.pop()
elif ele not in li:
cur.append(ele)
bt(cur)
cur.pop()
bt(cur)
return res
if __name__ == '__main__':
so = Solution()
print(so.permute([1, 2, 3]))
The running result of this snippet shows the res
has been successfully referenced since they shown the same id value. Why the fla
one doesn't work?