-
Notifications
You must be signed in to change notification settings - Fork 0
102. Binary Tree Level Order Traversal #28
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
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.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
個人的にはappend_if_existsで左右のノードを調べるほうが良いかと思いました。
There was a problem hiding this comment.
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_の接頭辞は無くてもいいか? | ||
|
There was a problem hiding this comment.
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 = [] |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
valuesだけだと、同じ深さのnodeの値をまとめた配列、という内容には少し物足りない気がしました。level_valueとかでしょうか?
There was a problem hiding this comment.
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という名前が微妙なのかもしれない)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
良いと思います。
https://leetcode.com/problems/binary-tree-level-order-traversal/description/