Conversation
| checkPathSum(node.left, current_sum) | ||
| checkPathSum(node.right, current_sum) |
There was a problem hiding this comment.
こうすると途中で hasTarget が見つかったとしても、計算が打ち切られずに続きますね。
| return (self.hasPathSum(root.left, targetSum - root.val) or | ||
| self.hasPathSum(root.right, targetSum - root.val)) |
|
|
||
| def checkPathSum(node: Optional[TreeNode], current_sum: int): | ||
| nonlocal hasTarget | ||
| if node is None or hasTarget: |
There was a problem hiding this comment.
これらは (node が null) と (ターゲットを発見済み) という別々の条件なので、私だったら2つ別のif文にしますが、ひとまとまりにしてしまう方も多くいらっしゃるとは思います。
There was a problem hiding this comment.
確かに分けた方がよりそれぞれの目的が明確になりますね
|
|
||
| self.checkPathSum(root, current_sum)を呼ぶタイミングがどこが適切かがわからない。今の場合だとまだ定義されていないから呼べないよと怒られる。 | ||
|
|
||
| hasTarget = (current_sum == turgetSum) |
There was a problem hiding this comment.
hasTarget = hasTarget or (current_sum == targetSum)
がやりたかった事ですかね?
|
|
||
| leafで判定するとより良い¥ | ||
|
|
||
| 合計を渡す代わりに残りのtargetを減らすやり方の方が賢かった |
There was a problem hiding this comment.
これは、引き継ぐ情報として合計か、合計の補数のようなものを選ぶか、というような考え方に抽象化して考えられます。
引き継ぐ情報の量を減らすためによくある考え方と思います。これの自然な発想法としては、Treeの方を小さくして次に渡すので、合計の方も小さくして次に渡す、といった考え方もあります。
| @@ -0,0 +1,31 @@ | |||
| # step1を修正したVersion | |||
| # Time Complexity: O(n) | |||
There was a problem hiding this comment.
この表記を見てしばらく、最悪は容易だが平均がこうなるのを示すのは少し難しいかも?などと色々考えていたのですが、実は木の形を固定した場合にTrue/Falseや見つかる位置などと計算量がほぼ無関係なので、どんな場合を考えてもO(n)ですね。(感想です)
|
|
||
| def checkPathSum(self, node: Optional[TreeNode], current_sum: int): | ||
| # leafまで辿り着いた時がnode is None、この時のcurrent_sumがtargetSumと一致しているかをチェック | ||
| if node is None: |
There was a problem hiding this comment.
early return してネストを下げたほうが読みやすいかなと思いました。
if node is None:
hasTarget = (current_sum == targetSum)
return
current_sum += int(node.val)
self.checkPathSum(node.left, current_sum)
self.checkPathSum(node.right, current_sum)
問題リンク
https://leetcode.com/problems/path-sum/description/
問題文の概要
Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
A leaf is a node with no children.
次に解く予定の問題
https://leetcode.com/problems/binary-tree-level-order-traversal/description/