104 Maximum Depth of Binary Tree#21
Open
MA-yo-TA wants to merge 3 commits into
Open
Conversation
h-masder
reviewed
Jul 1, 2026
| nodes = next_layer | ||
| next_layer = [] | ||
|
|
||
| return depth |
There was a problem hiding this comment.
next_layerの初期化はまとめられそうです。
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
nodes = [root]
depth = 0
while nodes:
depth += 1
next_layer = []
for node in nodes:
if node.left is not None:
next_layer.append(node.left)
if node.right is not None:
next_layer.append(node.right)
nodes = next_layer
return depth
Owner
Author
There was a problem hiding this comment.
ありがとうございます。
個人的には nodes と next_layer の初期化・更新はセットでやりたい感覚(今の階層 vs. 次の階層、という対の意識)があってこう書いたのですが h-masder さんの感覚だとどうですか?
nodes はループ中も一貫した意味を持つ名前なのに対して next_layer は while のループ一回ごとに完結して意味を持つのでループ内だけに存在してて欲しい(からまとめる)というのもわかります。
There was a problem hiding this comment.
私としては、next_layer はループの中で毎回作るものというイメージがあるので、中で初期化しています。
とはいえ、このあたりは好みの問題で、どちらの書き方でもいいのかなと思っています。
感覚としては、「各ループの最初に next_layer を空にして使い始める」か、「ループの最後に次のループのために空にしておく(後片付けしておく)」かという違いで、どちらの考え方もよくわかります。
Owner
Author
There was a problem hiding this comment.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
この問題:https://leetcode.com/problems/maximum-depth-of-binary-tree/
次の問題:https://leetcode.com/problems/minimum-depth-of-binary-tree/