Skip to content

Conversation

garunitule
Copy link
Owner

result = []
nodes = [root]
while nodes:
result.append([node.val for node in nodes])
Copy link

@huyfififi huyfififi Aug 10, 2025

Choose a reason for hiding this comment

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

個人的には、resultに先に追加してもfor loop内で追加していってもコードの読みやすさにあまり違いを感じなかったので、nodesを2回走査していることの方が少し気になりましたが、他の方々の感覚も気になるところですね 👀
(制約を見るに、一つの階層にあるNodeの数は小さく、2回走っても大した問題ではないですが。。)

Choose a reason for hiding this comment

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

横から失礼します。nodes には同じレベルのノードが保存されていると思うので、好みかもしれませんが私も下の for ループ内で一緒に処理をしたいと思いました。

class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if root is None:
return []

Choose a reason for hiding this comment

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

step1 では、ここで 空の list で初期化された result を返されていましたが、自分もここでは [] を返すのが好みです。

next_level_nodes.append(node.right)
nodes = next_level_nodes
return result
```

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.

4 participants