我找到了Leetcode NO的解决方案。 543 使用全局变量求解的二叉树直径。我有下面文字中显示的解决方案。作者使用标量变量“self.res”来存储最终答案,该答案在程序遍历给定二叉树时更新。
我想知道为什么作者需要使用 self.res
而不是通用整型变量(例如仅 res
)来存储答案;当我用 res 替换 self.res 时,答案是错误的。谁能指出其中的区别吗?
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
self.res = 0
def depth(root):
if not root:
return 0
left = depth(root.left)
right = depth(root.right)
self.res = max(self.res, left + right)
return max(left, right) + 1
depth(root)
return self.res
最佳答案
严格来说,它不一定是属性。它可能是一个非局部变量。
class Solution:
def diameterOfBinaryTree(self, root: TreeNode) -> int:
<b>res = 0</b>
def depth(root):
<b>nonlocal res</b>
if not root:
return 0
left = depth(root.left)
right = depth(root.right)
<b>res</b> = max(<b>res</b>, left + right) # the key to memorize the result
return max(left, right) + 1
depth(root)
return <b>res</b>
如果没有 nonlocal
语句,res
将是一个局部变量,在 深度
第一次尝试在调用max
。
Python 2 没有 nonlocal
语句,因此实例属性是全局变量的最佳替代方案,用于在 深度
调用之间保留状态。 (类型提示表明这可能不是为 Python 2 编写的,但旧习惯很难改掉。)在 Python 3 中,使用 nonlocal
,上面甚至不再使用 self
,因此 diameterOfBinaryTree
可以简单地编写为常规函数,而不是不必要的类的实例方法。
关于python - 类内部定义的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59417429/