質問編集履歴
1
追加
title
CHANGED
File without changes
|
body
CHANGED
@@ -17,11 +17,31 @@
|
|
17
17
|
return 0
|
18
18
|
|
19
19
|
if not node.left and not node.right:
|
20
|
-
self.max_depth = max(self.max_depth, depth)
|
20
|
+
self.max_depth = max(self.max_depth, depth) ###
|
21
21
|
else:
|
22
22
|
helper(node.left, depth + 1)
|
23
23
|
helper(node.right, depth + 1)
|
24
24
|
|
25
25
|
helper(root, 1)
|
26
26
|
return self.max_depth
|
27
|
+
```
|
28
|
+
|
29
|
+
言葉足らずでした。ehshellさんがおっしゃる通り、全てのselfを外すという解釈で正しいです。
|
30
|
+
その時の" local variable 'max_depth' referenced before assignment "エラーは、
|
31
|
+
当然ですが###の部分で出ます。
|
32
|
+
selfを外すと、max_depthローカル変数として扱われるということはわかりました。
|
33
|
+
|
34
|
+
ただ、self.max_depth=0 は、maxDepth関数内で宣言されています。
|
35
|
+
グローバル変数は、関数外でイニシャライズするものとばかり思っていたのですが、
|
36
|
+
上記のような形で、グローバル変数をイニシャライズすることも多いのでしょうか。
|
37
|
+
例えば今回の場合では、`
|
38
|
+
```Python
|
39
|
+
def __init__(self):
|
40
|
+
self.max_depth = 0
|
41
|
+
|
42
|
+
def maxDepth(self, root: Optional[TreeNode]) -> int:
|
43
|
+
#以下、略
|
44
|
+
```
|
45
|
+
のようにするのが作法と思っていましたが、そうでもないのでしょうか。
|
46
|
+
|
27
47
|
```
|