102. Binary Tree Level Order Traversal#40
Conversation
| if node.left: | ||
| pending_nodes.append(node.left) | ||
| if node.right: | ||
| pending_nodes.append(node.right) |
There was a problem hiding this comment.
if node is not Noneを使う方がよさそうです。
There was a problem hiding this comment.
確かに if node is not None の方が安全ですね。
| if root is None: | ||
| return [] | ||
|
|
||
| level_order = [] |
There was a problem hiding this comment.
level_orderを一番最初に定義しておけば、root is None の返り値としても使用可能になると思いました。
There was a problem hiding this comment.
確かにおっしゃる通りですね。
読みやすさとしては議論の余地がありますが、以下のようにするとガード節自体をなくせることに気がつきました。
pending_nodes = deque([root] if root else [])There was a problem hiding this comment.
個人的には、 early return を先に書いたほうが、読み手に取って読みやすくなると思います。理由は、関数の宣言と early return のあいだにコードが挟まっていると、そのコードの内容を early return のコードを読むあいだ、短期記憶にとどめておかなければならないためです。
また、level_order を最初に定義し、 root is None の返り値として使用した場合、 level_order の定義を思い返さなければなりません。これは、小規模ではありますが、ややパズルに感じます。
| if root is None: | ||
| return [] | ||
|
|
||
| level_by_level = [] |
There was a problem hiding this comment.
level_values values_at_level といった変数名も考えられそうです。このあたり、自分には英語のニュアンスの違いが分かりませんでした。申し訳ありません。
There was a problem hiding this comment.
この命名 level_by_level に関しては、「レベルの中にレベルがある」を意図しました。意図が伝わらなさそうでしたのでStep3では改善しました。
| if root is None: | ||
| return [] | ||
|
|
||
| level_order = [] |
There was a problem hiding this comment.
個人的には、 early return を先に書いたほうが、読み手に取って読みやすくなると思います。理由は、関数の宣言と early return のあいだにコードが挟まっていると、そのコードの内容を early return のコードを読むあいだ、短期記憶にとどめておかなければならないためです。
また、level_order を最初に定義し、 root is None の返り値として使用した場合、 level_order の定義を思い返さなければなりません。これは、小規模ではありますが、ややパズルに感じます。
102. Binary Tree Level Order Traversal
次回予告: 103. Binary Tree Zigzag Level Order Traversal