Skip to content

Conversation

@skypenguins
Copy link
Owner

@skypenguins skypenguins commented Aug 4, 2025

112. Path Sum

次回予告: 121. Best Time to Buy and Sell Stock

@skypenguins skypenguins self-assigned this Aug 4, 2025
if root is None:
return False

node_and_val = [(root, root.val, root.val)]

Choose a reason for hiding this comment

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

root.valroot からアクセスできるのでスタックに積む必要はないと思います。node_and_path_sum などにするとよさそうですね (最初、2, 3 番目の要素が何を示しているのか戸惑いました)。

node_and_val = [(root, root.val, root.val)]

while node_and_val:
node, val, sum = node_and_val.pop()

Choose a reason for hiding this comment

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

組み込みの sum を上書きしているので、避けたほうがいいですね。path_sum とするか、やむを得なければ sum_ でしょうか。

https://peps.python.org/pep-0008/#descriptive-naming-styles

single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g. :
tkinter.Toplevel(master, class_='ClassName')

return False

targetSum = targetSum - root.val
if targetSum == 0 and root.left is None and root.right is None:

Choose a reason for hiding this comment

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

細かいしどちらでもいいですが、

if root.left is None and root.right is None and targetSum == 0:
    ...
if root.left is None and root.right is None:
    if targetSum == 0:
        ...

としたくなりますね。葉であるかどうかが前提条件なおで先にチェックしたいです。

if node.left is None and node.right is None:
if sum == targetSum:
return True
if node.right:

Choose a reason for hiding this comment

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

None であるか確認している場合とそうでない場合が混在している点が気になりました。
また、L20 では left を先に書いていて、L23-26 では right を先に書いている点も少し気になりました。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants