Open
Conversation
sakupan102
reviewed
Jun 27, 2024
| while nodes: | ||
| node = nodes.popleft() | ||
| current_level_values.append(node.val) | ||
| append_if_exists(next_level_nodes, node.left) |
There was a problem hiding this comment.
個人的にはappend_if_existsで左右のノードを調べるほうが良いかと思いました。
Owner
Author
There was a problem hiding this comment.
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関数名はもう少しあるかもですが、こんな感じですかね?発想なかったんですがなるほどと思いました。スッキリすると思います
Mike0121
reviewed
Jun 29, 2024
|
|
||
| 再帰。最悪2000回スタックに積まれるので環境によってはRecursionError。 | ||
| 変数名が全体的に長いのでゴチャ付いてる感じがある。やっぱりcurrent_level_の接頭辞は無くてもいいか? | ||
|
|
There was a problem hiding this comment.
currentに関して、自分のPRで以前コメントをいただいたのでリンク貼っておきます。
Mike0121/LeetCode#7
Mike0121
reviewed
Jun 29, 2024
| level_order_values = [] | ||
| while nodes: | ||
| next_level_nodes = [] | ||
| values = [] |
There was a problem hiding this comment.
valuesだけだと、同じ深さのnodeの値をまとめた配列、という内容には少し物足りない気がしました。level_valueとかでしょうか?
Owner
Author
There was a problem hiding this comment.
配列なので level_values ですかね?自分もvaluesは微妙だなと思いつつ、ギリギリ分かるかなと思ってこうしてみてました。
level_valuesだとlevel_order_valuesとの棲み分けが分かりにくくなるかも?とは思いましたが...うーんどうなんですかね (level_order_valuesという名前が微妙なのかもしれない)
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/binary-tree-level-order-traversal/description/