Skip to content

104 Maximum Depth of Binary Tree#21

Open
MA-yo-TA wants to merge 3 commits into
mainfrom
104-Maximum-Depth-of-Binary-Tree
Open

104 Maximum Depth of Binary Tree#21
MA-yo-TA wants to merge 3 commits into
mainfrom
104-Maximum-Depth-of-Binary-Tree

Conversation

@MA-yo-TA

@MA-yo-TA MA-yo-TA commented Jul 1, 2026

Copy link
Copy Markdown
Owner

nodes = next_layer
next_layer = []

return depth

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。
個人的には nodesnext_layer の初期化・更新はセットでやりたい感覚(今の階層 vs. 次の階層、という対の意識)があってこう書いたのですが h-masder さんの感覚だとどうですか?

nodes はループ中も一貫した意味を持つ名前なのに対して next_layer は while のループ一回ごとに完結して意味を持つのでループ内だけに存在してて欲しい(からまとめる)というのもわかります。

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

私としては、next_layer はループの中で毎回作るものというイメージがあるので、中で初期化しています。

とはいえ、このあたりは好みの問題で、どちらの書き方でもいいのかなと思っています。

感覚としては、「各ループの最初に next_layer を空にして使い始める」か、「ループの最後に次のループのために空にしておく(後片付けしておく)」かという違いで、どちらの考え方もよくわかります。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Shunii85 Shunii85 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

いいと思いました。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants