0

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?

  • 1
    Your variable `po` is not global, it is a class variable. If you want it to be global, it should be declared at the top level. – kaya3 Mar 15 '23 at 23:34
  • 1
    It's a class variable: `Solution.po += 1` if you want the result shared across all instances of `Solution`, otherwise `self.po += 1`. In the `nonlocal`case you actually declared the variable nonlocal, so it modified the variable in the outer scope. – Mark Tolonen Mar 15 '23 at 23:48
  • @kaya3 I did like you said and defined at the top before using global keyword. This time got an index out of range error in this line: root = TreeNode(preorder[po]). Why this is the case? I guess po get a garbage value but i am not sure. What is wrong here? – Arman Engin Sucu Mar 16 '23 at 00:18

0 Answers0