Skip to content

112.path sum#24

Open
tom4649 wants to merge 3 commits intomainfrom
112.Path-Sum
Open

112.path sum#24
tom4649 wants to merge 3 commits intomainfrom
112.Path-Sum

Conversation

@tom4649
Copy link
Copy Markdown
Owner

@tom4649 tom4649 commented Mar 16, 2026

112/sol1.py Outdated
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if root is None:
return False
diff = 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.

まあ差分 (difference) であることはそうなんですが、new_target_sum みたいな命名が分かりやすいように感じました。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

remaining などでもいいかもしれません。

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.

remainingを採用しようと思います。diffは分かりづらいですね。

112/sol2.py Outdated
return node.left is None and node.right is None

def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
que = deque()
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

中途半端な省略はしないほうが無難かと思います。この練習会では frontier という命名もよく見かけます。

Suggested change
que = deque()
queue = deque()

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.

frontierに慣れたいのもあるのでこちらを採用しようと思います。

112/sol2.py Outdated
Comment on lines +21 to +28
if node is None:
continue
current_sum += node.val
if self.is_leaf(node) and current_sum == targetSum:
return True
for child in [node.left, node.right]:
if child is not None:
que.append((child, current_sum))
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nodeNoneチェックをするなら、childも気にせずappendしてしまえば良いと思いました。反対に、append時にNoneチェックするなら、関数の冒頭で root is None チェックをすれば良いと思います。

112/sol2.py Outdated
que = deque()
que.append((root, 0))
while que:
node, current_sum = que.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.

末尾からpopするなら、dequeではなくてstack (list) でも良さそうですね。

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.

2 participants