Conversation
| sakupan102: https://github.com/sakupan102/arai60-practice/pull/26#discussion_r1593805972 | ||
|
|
||
| ・phase1ではtargetSumを更新して0かどうかを判断していたが, 葉だったらtargetSum == root.valかどうかを返してそれ以外はrest = targetSum - root.valとして処理する方が好みだったので書き換える。 | ||
| ・|演算子よりかはor演算子の方が良いか(|はビット演算子, orの方がboolを扱う時の方では馴染みがありそう...?) |
There was a problem hiding this comment.
補足程度に...。
https://docs.python.org/3.12/library/stdtypes.html#boolean-type-bool
For logical operations, use the boolean operators and, or and not. When applying the bitwise operators &, |, ^ to two booleans, they return a bool equivalent to the logical operations “and”, “or”, “xor”. However, the logical operators and, or and != should be preferred over &, | and ^.
とあるので、 "and", "or", "!=" を使う方が好まれるようです
| targetSum = targetSum - root.val # update targetSum | ||
| if targetSum == 0 and not root.right and not root.left: | ||
| return True | ||
| return self.hasPathSum(root.right, targetSum) | self.hasPathSum(root.left, targetSum) |
There was a problem hiding this comment.
問題文にbinary tree, The number of nodes in the tree is in the range [0, 5000].とあったので木の高さは深くてもlog_2(n)ぐらいだろうと思いましたが, 片方に偏る場合もテストケースとして考えられるので再帰回数増やすかやめた方が良さそうですね...
| def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: | ||
| stack = [(root, targetSum)] | ||
| while stack: | ||
| node, current_sum = stack.pop() |
There was a problem hiding this comment.
好みかもですが、dequeにしてpopleftにした方が、BFSにするのであれば素直な処理の順番になると思いました。
There was a problem hiding this comment.
今回はDFSのつもりで書いたのですがどうでしょうか....?
There was a problem hiding this comment.
すみません、きちんとDFSになっています。
BFSであればあとのappendの順番も変更する必要がありますね。再帰の解法がDFSだったので、BFSの解法を載せているのかなと勝手に思ってしまいました。
的外れなレビューをして混乱を招いてしまい、大変申し訳御座いません。
|
良いと思いました。 |
| if not node.right and not node.left and node.val == current_sum: | ||
| return True | ||
|
|
||
| rest = current_sum - node.val |
There was a problem hiding this comment.
これ、引き算先にしちゃって、
if not node.left and not node.right:
return rest == 0のほうが素直ではないでしょうか。
There was a problem hiding this comment.
その訂正の仕方だと, まだ探索しきっていない葉のうち, rest == 0となるものがあるのにrest != 0となるものが先に判定に来ると間違った回答を出してしまう気がします。rest = current_sum - node.valを先にしましょうというのは, その通りかもしれません。
There was a problem hiding this comment.
この場合は、node.left, node.right がともに None なのでいいんじゃないですか。
There was a problem hiding this comment.
再帰ではなく、iterativeな解法なので、ここでreturnすると最終結果になってしまいます。
正しくはこんな感じでしょうか。
if not node.left and not node.right and rest == 0:
return True
問題
112. Path Sum