为什么对于int值只有一个引用之前的赋值错误,而在嵌套函数中却没有列表?

问题描述

我正在执行leetcode问题-rightSideView。当我创建一个内部辅助函数时,我以为我可以访问外部函数变量。但是,这仅适用于结果(列表),而不适用于maxHeight(int)。下面引用的代码

class Solution(object):
    def rightSideView(self,root):
       result = []
       maxHeight = 0
       def dfs(node,height):
           if node is not None:
               height += 1
               if height > maxHeight:
                   maxHeight = height
                   result.append(node.val)
               dfs(node.right,height)
               dfs(node.left,height)
       dfs(root,0)
       return result

如果我引用self.maxHeight,则可以解决此问题;但是我不必为结果做同样的事情。为什么是这样?列表是否可以在python类中创建为全局变量?不知道该怎么解释。

以下代码可以正常运行:

class Solution(object):
    def rightSideView(self,root):
       result = []
       self.maxHeight = 0
       def dfs(node,height):
           if node is not None:
               height += 1
               if height > self.maxHeight:
                   self.maxHeight = height
                   result.append(node.val)
               dfs(node.right,0)
       return result

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...