-
Notifications
You must be signed in to change notification settings - Fork 0
112. Path Sum #17
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?
112. Path Sum #17
Conversation
| if root is None: | ||
| return False | ||
|
|
||
| node_and_val = [(root, root.val, root.val)] |
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.
root.val は root からアクセスできるのでスタックに積む必要はないと思います。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() |
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.
組み込みの 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: |
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.
細かいしどちらでもいいですが、
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: |
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.
None であるか確認している場合とそうでない場合が混在している点が気になりました。
また、L20 では left を先に書いていて、L23-26 では right を先に書いている点も少し気になりました。
112. Path Sum
次回予告: 121. Best Time to Buy and Sell Stock