Conversation
|
|
||
| if not root: | ||
| return False | ||
| node_target_pairs = [(root, targetSum)] |
There was a problem hiding this comment.
好みの問題のような気もしますが、ここの初期化はnode_target_pairs = [(root, 0)]とかにして足していった方が分かりやすいような気がしました。
There was a problem hiding this comment.
いえいえ、ありがとうございます。自分はtargetSumから引いてくやり方の方が分かりやすいと感じたので、やはり好みじゃないかな、とは思います
There was a problem hiding this comment.
言い回しが分かりづらいものになっていたので一応追記。
やはり好みじゃないかな、とは思います
は好みの問題だと思う、という意味です。
There was a problem hiding this comment.
自分の場合は再帰の実装が頭のベースにあったので引く方が自然に感じました(が、好みだと思います)
| node, target = node_target_pairs.pop() | ||
| if is_leaf(node) and node.val == target: | ||
| return True | ||
| if node.left: |
There was a problem hiding this comment.
ここでNoneかどうかの判定をするのではなく上でnode is Noneの場合にcontinueさせるのも選択肢の一つですかね。
| return False | ||
| return self._has_path_sum_helper(root, targetSum) | ||
|
|
||
| def _has_path_sum_helper(self, node: TreeNode, target: int) -> bool: |
There was a problem hiding this comment.
この関数はhasPathSum内でしか使わないと思うので内部に定義してもよい気がしました。
There was a problem hiding this comment.
内部で定義すると、毎回、関数が呼ばれるたびに関数が生成されて、nonlocal な変数が読めますね。よしあしは色々でしょう。
| if is_leaf(node): | ||
| return total + node.val == targetSum | ||
| total += node.val |
There was a problem hiding this comment.
total += node.valを先にしてから、
return total == targetSumした方が素直だと思いました。
| return False | ||
| return self._has_path_sum_helper(root, targetSum) | ||
|
|
||
| def _has_path_sum_helper(self, node: TreeNode, target: int) -> bool: |
There was a problem hiding this comment.
関数内でもずっとrestの意味で使っているように思えるので、引数名はtargetでなく最初からrestにした方がいいと思いました。
| if node.right: | ||
| node_target_pairs.append((node.right, rest)) | ||
| return False | ||
| ``` |
There was a problem hiding this comment.
全体的に良いと思いました。自分もレビューのために解き直した際は、targetSumから引いていく形で実装しました。好みの問題であることに賛成です。
https://leetcode.com/problems/path-sum/description/