Skip to content

112. Path Sum#25

Open
TakayaShirai wants to merge 1 commit intomainfrom
112_path_sum
Open

112. Path Sum#25
TakayaShirai wants to merge 1 commit intomainfrom
112_path_sum

Conversation

@TakayaShirai
Copy link
Copy Markdown
Owner

@TakayaShirai TakayaShirai self-assigned this Feb 16, 2026
// ----------------------------
// Skewed Tree のテスト
// 再帰はスタックオーバーフローしやすいので、小さいサイズのみ
// 大きいサイズは BFS のみで測定
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

通りすがりに失礼します。
DFSはstackで書けて、これはBFS同様にスタックオーバーフローを気にせずできます。
知っていらしたら問題ないです。

Comment on lines +26 to +29
// 感覚的には木の構造によって、幅優先探索と、深さ優先探索を使い分けるのが良さそうだが、
// 感覚の域を出ない。そもそもあっているかもわからない。
// 浅いルートが多いやつだったり一本だけ驚異的に長いルートがあるなどの、長さに差がある木は、幅優先探索で、
// あまり長さに差がない木は、深さ優先探索を選んだ方が良さそう。
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

条件を満たす葉ノードが存在する浅さにも左右される気がしました。結局探索してみるまで分からないように思います。


total += node.val;

if (isLeaf(node) && total == targetSum) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

node == null の場合を直前で弾いているので、isLeaf は non-null の node のみを受け付けるようにして良いと思いました。そうすると関数ではなくbooleanでも良さそうです。

また関数 isLeaf について、nodeがnullのときの挙動を仕様として与えてしまうと、後で変更するのが難しくなってしまうのも気になりました(変更したときに、呼び出し元の挙動を気にする必要が出てくる)。

Comment on lines +103 to +116
var (node, total) = nodeWithTotal.removeFirst();

if (node == null) {
continue;
}

total += node.val;

if (isLeaf(node) && total == targetSum) {
return true;
}

nodeWithTotal.add((node.left, total));
nodeWithTotal.add((node.right, total));
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
var (node, total) = nodeWithTotal.removeFirst();
if (node == null) {
continue;
}
total += node.val;
if (isLeaf(node) && total == targetSum) {
return true;
}
nodeWithTotal.add((node.left, total));
nodeWithTotal.add((node.right, total));
// キューから取り出す。nullなら飛ばす
var (node, total) = nodeWithTotal.removeFirst();
if (node == null) {
continue;
}
// 現在のノードが条件を満たすかチェック
total += node.val;
if (isLeaf(node) && total == targetSum) {
return true;
}
// 子ノードに引き継ぐ
nodeWithTotal.add((node.left, total));
nodeWithTotal.add((node.right, total));

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