Skip to content

112. Path Sum#27

Open
xbam326 wants to merge 3 commits into
mainfrom
112
Open

112. Path Sum#27
xbam326 wants to merge 3 commits into
mainfrom
112

Conversation

@xbam326
Copy link
Copy Markdown
Owner

@xbam326 xbam326 commented Feb 14, 2026

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

動詞の原型を変数名に付けると、関数名のように感じられます。 accumulated はいかがでしょうか?

frontier.append((root, total_val))

while frontier:
frontier_node, val = frontier.popleft()
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 から pop したので、これ以降は frontier_ が無くても大丈夫そうです。

Suggested change
frontier_node, val = frontier.popleft()
node, val = frontier.popleft()

if is_leaf and val == targetSum:
return True

if frontier_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.

冒頭で root is None 判定しているなら、ここでも is not None と判定するほうが、一貫性があって良いと思います。
反対に冒頭を not root でも良いです。

Comment on lines +22 to +24
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.

ここ、左右対称な話なのに、フォーマッタに整形させると非対称みたいに見えちゃうんですよね…。

Suggested change
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(
root.right, targetSum - root.val
)
left_has_path_sum = self.hasPathSum(root.left, targetSum - root.val)
right_has_path_sum = self.hasPathSum(root.right, targetSum - root.val)
return left_has_path_sum or right_has_path_sum

のような選択肢も幅として持っておくといいのかもな、と思いました。

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