Skip to content

【Arai60】25問目 112. Path Sum#25

Merged
shining-ai merged 3 commits intomainfrom
review25
Jun 30, 2024
Merged

【Arai60】25問目 112. Path Sum#25
shining-ai merged 3 commits intomainfrom
review25

Conversation

@shining-ai
Copy link
Copy Markdown
Owner

if not root:
return False
if not root.left and not root.right:
if root.val == targetSum:
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

return root.val == targetSum としたほうが、 root.val != targetSum だった場合の無駄な処理が省けて良いと思います。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

おっしゃるとおり葉ノードの先まで調べようとして無駄ですね。

def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
node_sum_stack = [(root, 0)]
while node_sum_stack:
node, path_sum = node_sum_stack.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.

L18とL21でpath_sumの意味が変わっているかなと思いました。それぞれprev_path_sum, current_path_sumとかはどうでしょうか?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

中身が変わっているので、混乱のもとになりますね。
提案していただいた変数を使ったほうが分かりやすくなると思いました。

@shining-ai shining-ai merged commit be5897b into main Jun 30, 2024
@shining-ai shining-ai deleted the review25 branch June 30, 2024 03:02
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.

3 participants