I have been doing Leetcode and I came across one issue. Its a program which finds the max Diameter of a Binary Tree. I have a class which has a nested function in it. For the class : diameterOfBinaryTree(obj), I have declared a Global variable for function: dfs(), global variable named 'dia' of type Int. When I try to access it inside dfs(), it throws me Unbound local error "UnboundLocalError: local variable 'dia' referenced before assignment"
But, when I change the variable to list and use the 0th index for the same computation, it works fine. Below is the code for functionality with Int variable
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
dia=0
def dfs(root):
print(dia)
if not root:
return -1
left=dfs(root.left)
right=dfs(root.right)
dia=max(dia,2+left+right)
return 1+ max(left, right)
dfs(root)
return dia
This is the code using List.
class Solution(object):
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def dfs(root):
print(dia[0])
if not root:
return -1
left=dfs(root.left)
right=dfs(root.right)
dia[0]=max(dia[0],2+left+right)
return 1+ max(left, right)
dia=[0]
dfs(root)
return dia[0]
The 2nd code works but the first doesnt. The same approach works for list but not for variables. Am I missing anything?