0
class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        
        res = [0]
        
        def dfs(root):
            if not root:
                return -1
            left = dfs(root.left)
            right = dfs(root.right)
            res[0] = max(res[0], 2 + left + right)
            return 1 + max(left, right)
        dfs(root)
        return res[0]

Why can't we access res (if its a variable) inside that function?

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • You should copy and paste the exact error you get into your question. – Mark Ransom Sep 03 '22 at 02:57
  • My guess is that you're looking at https://stackoverflow.com/questions/4693120/why-isnt-the-global-keyword-needed-to-access-a-global-variable, but without seeing the exact code it's only a guess – Silvio Mayolo Sep 03 '22 at 02:59
  • Welcome to Stack Overflow! Please take the [tour]. For help with a code problem, you need to make a [mre]. Here, I'm skimming the code and everything related to `res` looks fine, but I can't verify because `TreeNode` is not defined. But, it also seems like you're asking about trying to **assign** to `res` inside `dfs()`, which is not even in the code here. Please show us what you tried. BTW, if you want more tips, like how to write a good title, see [ask]. – wjandrea Sep 03 '22 at 03:16

1 Answers1

0

I suspect you are getting "local variable referenced before assignment". If so, this is because you are using nonlocal variables and python is deciding some of your code is making that variable name local. The short story is, make the variables nonlocal explicitly using "nonlocal" function. The answer why arrays work and variables dont is that you can add elements to an array without changing the array. Here is some sample code that shows what works and what doesn't. It can behave in very non obvious ways, since "a += [3]" assigns a new array when "a.append(3)" doesn't. which has a big impact in this scenario. But use the nonlocal keyword and you will get the exact behavior you expect.

#!/usr/bin/python

def foo():
    var = "a"
    array = [0]

    # will work
    def test1():
        print(var)
    # will break, becase var is local, even thought assigned happens later
    def test2():
        print(var)
        var = "b"
    # works because we told python var is nonlocal
    def test3():
        nonlocal var
        print(var)
        var = "b"
    # breaks because we are actually assigning the array
    def test4():
        print(array[0])
        array += [3]
    # works becase array is not local
    def test5():
        nonlocal array
        print(array[0])
        array += [3]
    # works because we are not assiging the array
    def test6():
        print(array[0])
        array.append(3)
    # works becasuse we are not assigning the arry
    def test7():
        print(array[0])
        array[0] = [3]

    test7()

foo()



toppk
  • 696
  • 4
  • 10