问题描述
我正在执行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 (将#修改为@)