112. Path Sum#25
Conversation
| queue.append((node.left, current_sum - node.val)) | ||
| if node.right: | ||
| queue.append((node.right, current_sum - node.val)) | ||
| return False |
There was a problem hiding this comment.
特に問題ないと思いました。
if node.left is None and node.right is None and current_sum == node.val: の部分は、step3 BFSのようにis_leafを別で定義してあげている方がすっきりしていて好みです。
thonda28
left a comment
There was a problem hiding this comment.
再帰、Stack、Queue のどのパターンも全体的によさそうに思いました
| return False | ||
|
|
||
| if root.left is None and root.right is None: | ||
| return targetSum == root.val |
There was a problem hiding this comment.
root.val が左辺にある方が自然かなと思いました。root.val が targetSum に等しいかどうか、という書き方のほうが自然言語と近く、可読性が高い気がします。
|
|
||
| if node.right: | ||
| node_and_sum.append((node.right, current_sum - node.val)) | ||
| if node.left: |
There was a problem hiding this comment.
細かいですが、if node.left is None と if node.left とで判定に None を使ったり使わなかったりなのが気になりました。どちらかに統一して一貫性をもたせるとよりよさそうです
| if node is None: | ||
| return False | ||
|
|
||
| current_sum += node.val |
There was a problem hiding this comment.
この足し上げていく方法は deque を使う場合にも使えるので、こちらで気に入ったならば、あちらでも使えます。
| node_and_sum = [(root, targetSum)] | ||
|
|
||
| while node_and_sum: | ||
| node, current_sum = node_and_sum.pop() |
There was a problem hiding this comment.
一つ上の解法と比較して、current_sumという名前の役割が逆になっているので少し気になりました。
このコード単独だと気にならない気もしますが、こちらをremaining_sumなどとするのもよいかもしれません。
| return (self.hasPathSum(root.left, targetSum - root.val) or | ||
| self.hasPathSum(root.right, targetSum - root.val)) |
There was a problem hiding this comment.
今回はさして読みやすさが変わりませんが、こちらが参考になるかもしれません
https://peps.python.org/pep-0008/#should-a-line-break-before-or-after-a-binary-operator
https://leetcode.com/problems/path-sum/description/