Conversation
| if (isLeafNode && root.val == targetSum) { | ||
| return true; | ||
| } |
There was a problem hiding this comment.
if (isLeafNode) {
return root.val == targetSum;
}| if (isLeafNode && currentPathSum == targetSum) { | ||
| return true; | ||
| } |
There was a problem hiding this comment.
こちらの場合は currentPathSum == targetSum が false の場合は処理を継続しなければならないので、こんな感じでしょうか
if (isLeafNode) {
if (currentPathSum == targetSum) {
return true;
}
continue;
}There was a problem hiding this comment.
ありがとうございます!こちらも step 4 に記載しました
| if (root == null) { | ||
| return false; | ||
| } | ||
| boolean isLeafNode = root.left == null && root.right == null; |
There was a problem hiding this comment.
返信遅くなりました。
確認するのに時間が空いたからか、改めて見ると冗長に感じたので、変数に置かないように step 4 を修正しました。
| } | ||
|
|
||
| if (node.right != null) { | ||
| nodeStack.push(new NodeWithPathSum(node.right, currentPathSum)); |
There was a problem hiding this comment.
Java は最近(Tiger 以降)ほとんど書いていないのですが、record は null 入らないんでしたっけ。スタックには null も入るようにして、チェックを pop してから行うのも一つかと思いました。
There was a problem hiding this comment.
返信遅くなりました。
Null が入らないのは ArrayDeque の方になります。 Record はイミュータブルですが null を代入することは可能です。
確かに、別のクラスを使って、チェックを pop してから行うのも一つですが、経験上 null を許容しない設計になっているクラス (メンバ etc.) ないしコレクションの方が扱いやすかったので、こちらをあえて選んでいました。
There was a problem hiding this comment.
あれ、ArrayDeque は、null が入らないのはいいですが、null を要素に持つ Record も入らないということですか?
それとも、文法上はTreeNode node = nodeWithPathSum.node;の直後に null check をして、あと3箇所のチェックを消すというのも選択として可能ということですか。
There was a problem hiding this comment.
あ、すいません読み違えてました。Null であるフィールドを持つ record は許容されます (null だとだめなのは record のインスタンスでした)。ですので、スタックには null も入るようにして、チェックを pop してから行うのは可能です。
こんな実装になります (step 4 に記載しました)
class Solution {
private record NodeWithPathSum(TreeNode node, int pathSum) {};
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
Deque<NodeWithPathSum> nodeStack = new ArrayDeque<>();
nodeStack.push(new NodeWithPathSum(root, 0));
while (!nodeStack.isEmpty()) {
NodeWithPathSum nodeWithPathSum = nodeStack.pop();
TreeNode node = nodeWithPathSum.node;
if (node == null) {
continue;
}
int currentPathSum = node.val + nodeWithPathSum.pathSum;
if (node.left == null && node.right == null) {
if (currentPathSum == targetSum) {
return true;
}
continue;
}
nodeStack.push(new NodeWithPathSum(node.right, currentPathSum));
nodeStack.push(new NodeWithPathSum(node.left, currentPathSum));
}
return false;
}
}
https://leetcode.com/problems/path-sum/description/