I am a python newbie, so question could be so simple sorry for that already.
class Solution:
po = 0
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
dic = {v : i for i, v in enumerate(inorder)}
def helper(ios, ioe):
global po
if ios > ioe: return
root = TreeNode(preorder[po])
temp = dic[preorder[po]]
po += 1
root.left = helper(ios, temp - 1)
root.right = helper(temp + 1, ioe)
return root
return helper(0, len(preorder) - 1)
My question in the above code is: I was trying to modify integer value po inside the function helper. I was using C++ before and in python unlike C++ I can't pass integers pass by reference so I though I could modify the global int variable instead. However, the code doesn't work. I get the following error: "name 'po' is not defined. Did you mean: 'pow'?"
The program works if I change the code like the following(po is inside buildTree now and instead of global nonlocal used):
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
dic = {v : i for i, v in enumerate(inorder)}
po = 0
def helper(ios, ioe):
nonlocal po
if ios > ioe: return
root = TreeNode(preorder[po])
temp = dic[preorder[po]]
po += 1
root.left = helper(ios, temp - 1)
root.right = helper(temp + 1, ioe)
return root
return helper(0, len(preorder) - 1)
My question is why global doesn't work but nonlocal works, can you explain by giving the underlying logic please?