Skip to content

Conversation

fhiyo
Copy link
Owner

@fhiyo fhiyo commented Jun 27, 2024

while nodes:
node = nodes.popleft()
current_level_values.append(node.val)
append_if_exists(next_level_nodes, node.left)

Choose a reason for hiding this comment

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

個人的にはappend_if_existsで左右のノードを調べるほうが良いかと思いました。

Copy link
Owner Author

Choose a reason for hiding this comment

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

class Solution:
    def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        def append_if_child_exists(nodes: list[TreeNode], node: TreeNode):
            if node.left:
                nodes.append(node.left)
            if node.right:
                nodes.append(node.right)

        if not root:
            return []
        nodes = [root]
        level_order_values = []
        while nodes:
            values = []
            next_level_nodes = []
            for node in nodes:
                values.append(node.val)
                append_if_child_exists(next_level_nodes, node)
            nodes = next_level_nodes
            level_order_values.append(values)
        return level_order_values

関数名はもう少しあるかもですが、こんな感じですかね?発想なかったんですがなるほどと思いました。スッキリすると思います


再帰。最悪2000回スタックに積まれるので環境によってはRecursionError。
変数名が全体的に長いのでゴチャ付いてる感じがある。やっぱりcurrent_level_の接頭辞は無くてもいいか?

Choose a reason for hiding this comment

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

currentに関して、自分のPRで以前コメントをいただいたのでリンク貼っておきます。
Mike0121/LeetCode#7

level_order_values = []
while nodes:
next_level_nodes = []
values = []

Choose a reason for hiding this comment

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

valuesだけだと、同じ深さのnodeの値をまとめた配列、という内容には少し物足りない気がしました。level_valueとかでしょうか?

Copy link
Owner Author

Choose a reason for hiding this comment

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

配列なので level_values ですかね?自分もvaluesは微妙だなと思いつつ、ギリギリ分かるかなと思ってこうしてみてました。
level_valuesだとlevel_order_valuesとの棲み分けが分かりにくくなるかも?とは思いましたが...うーんどうなんですかね (level_order_valuesという名前が微妙なのかもしれない)

Copy link

@hayashi-ay hayashi-ay left a comment

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