注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
def dfs(root, depth):
# main process
depth += 1
if not root.left and not root.right:
self.result = max(depth, self.result)
# Rec
if root.left:
dfs(root.left, depth)
if root.right:
dfs(root.right, depth)
self.result = 0
dfs(root, 0)
return self.result
大家不用太细看这道题我的代码,我想问一个由这道题引申的一个概念问题。
这道题,如果我不这么定义self.result = 0,而是把result = 0写在class solution上面,然后在def dfs后面写global result。
那么最后这个代码对root = [1, null, 2]这个树的运行结果是3,而不是2。
目前目的就是想在dfs函数内部用一个外部变量,那么我目前看来定义self.也好,定义最上面然后用global也好,应该是一样的,可为什么只有self.是成功的?
|