Skip to content

112. Path Sum#25

Open
tarinaihitori wants to merge 2 commits into
mainfrom
112-path-sum
Open

112. Path Sum#25
tarinaihitori wants to merge 2 commits into
mainfrom
112-path-sum

Conversation

@tarinaihitori
Copy link
Copy Markdown
Owner

Comment thread 112. Path Sum.md
queue.append((node.left, current_sum - node.val))
if node.right:
queue.append((node.right, current_sum - node.val))
return False
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

特に問題ないと思いました。
if node.left is None and node.right is None and current_sum == node.val: の部分は、step3 BFSのようにis_leafを別で定義してあげている方がすっきりしていて好みです。

Copy link
Copy Markdown

@thonda28 thonda28 left a comment

Choose a reason for hiding this comment

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

再帰、Stack、Queue のどのパターンも全体的によさそうに思いました

Comment thread 112. Path Sum.md
return False

if root.left is None and root.right is None:
return targetSum == root.val
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

root.val が左辺にある方が自然かなと思いました。root.valtargetSum に等しいかどうか、という書き方のほうが自然言語と近く、可読性が高い気がします。

Comment thread 112. Path Sum.md

if node.right:
node_and_sum.append((node.right, current_sum - node.val))
if node.left:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

細かいですが、if node.left is Noneif node.left とで判定に None を使ったり使わなかったりなのが気になりました。どちらかに統一して一貫性をもたせるとよりよさそうです

Comment thread 112. Path Sum.md
if node is None:
return False

current_sum += node.val
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

この足し上げていく方法は deque を使う場合にも使えるので、こちらで気に入ったならば、あちらでも使えます。

Comment thread 112. Path Sum.md
node_and_sum = [(root, targetSum)]

while node_and_sum:
node, current_sum = node_and_sum.pop()
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

一つ上の解法と比較して、current_sumという名前の役割が逆になっているので少し気になりました。
このコード単独だと気にならない気もしますが、こちらをremaining_sumなどとするのもよいかもしれません。

Comment thread 112. Path Sum.md
Comment on lines +15 to +16
return (self.hasPathSum(root.left, targetSum - root.val) or
self.hasPathSum(root.right, targetSum - root.val))
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

今回はさして読みやすさが変わりませんが、こちらが参考になるかもしれません

https://peps.python.org/pep-0008/#should-a-line-break-before-or-after-a-binary-operator

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants