Conversation
| nodeとdepthを保持する構造体で管理 | ||
| 処理の一番最後(ループの外側)にreturn 0 を入れないと | ||
| error: non-void function does not return a value in all control pathと出る | ||
| これの回避方法が今の実装でいいのか疑問です |
There was a problem hiding this comment.
私C++詳しくないので的確なコメントが出来ずアレなんですが、とりあえずここ(L41)に到達し得る想定なのでしょうか?
ここら辺も参考になるかもなので貼っておきますね。
https://discord.com/channels/1084280443945353267/1226508154833993788/1227171332131786774
There was a problem hiding this comment.
これは、人間には帰納法から queue が空にならないことがいえますがコンパイラには分からないということですね。
while(1) にしてしまうのは一つでしょう。
There was a problem hiding this comment.
@TORUS0818
レビュー&&資料ありがとうございます。絶対に到達する認識で書いておりました。
「約束にない間違った使い方をしているのだから、そいつが悪い。驚くような動作をして、デバッグで苦労していても、私の問題ではない。」というのは好まれる態度ではないでしょう。
この部分は特に意識しないとですね。
Leetcodeではないと思いますが、いずれかの葉の左右のポインタがnullptrではなくrootを指し示していると(そもそも木ではなくなりますが)無限ループになってしまうので何らかのエラーを出したりした方が良さそうですね。
@oda
なるほどです。コンパイラ側からするとは、ツリーの1番下まで来るのか分からないからですね。
while(1)でも実装しました。
845fff1
| }; | ||
|
|
||
| public: | ||
| int minDepth(TreeNode* root) { |
There was a problem hiding this comment.
こちらの解法のようにnodeが常にnullptrでないパターンでも再帰で書いてもいいかもしれません。
There was a problem hiding this comment.
@fhiyo
レビューありがとうございます。
こちらどういうことか分かりませんでした🙇
bfsをqueueではなく再帰で書くということでしょうか?
There was a problem hiding this comment.
他の実装ではノードがnullの位置まで再帰で探索していますが、この実装のように最初にrootがnullかどうかだけを確認して、nullの位置までではなくnodeが存在する位置まで探索していくのを再帰で実装してもいいかも、という意味でした。
| int left_depth = minDepth(node->left); | ||
| int right_depth = minDepth(node->right); | ||
|
|
||
| if (node->left != nullptr && node->right == nullptr) { |
There was a problem hiding this comment.
if (!node->left && node->right) {
と書いても良いと思います。
There was a problem hiding this comment.
@nodchip
レビューありがとうございます。
確かにこちらの方が短く書けますね。
こちらで書いたものも実装しました。
111.MinimumDepthofBinaryTree/memo.md
Outdated
| 10^5であることを気を付ける | ||
| 許容されるデータ量について理解していないので調べてみた | ||
| =>スタックメモリが確保されオーバーフローを考慮する必要がある | ||
| スタックのデフォルトサイズは8mg |
There was a problem hiding this comment.
@Yoshiki-Iwasa
レビューありがとうございます。
参考にした下記の記事には8mbとあったのでmbだと思っていました。
https://stackoverflow.com/questions/2630054/does-c-limit-recursion-depth
There was a problem hiding this comment.
@Yoshiki-Iwasa
こちらの記事を見るとメモリ関連の時はMibとありますね。ということはRamの場合の単位はMibでしょうか?🙇
https://www.majordifferences.com/2018/03/differences-between-megabyte-and.html
There was a problem hiding this comment.
@liquo-rice @Yoshiki-Iwasa
なるほどです。失礼しました。修正しました🙇
There was a problem hiding this comment.
| queue<NodeAndDepth> candidates; | ||
| candidates.emplace(root, 1); | ||
| while (true) { | ||
| auto [node, depth] = std::move(candidates.front()); |
There was a problem hiding this comment.
NodeAndDepthのメンバがpointerとintのため、copy constructor呼び出しでも十分かなと思いました。
問題へのリンク
https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
問題文(プレミアムの場合)
備考
次に解く問題の予告
フォルダ構成
LeetCodeの問題ごとにフォルダを作成します。
フォルダ内は、step1.cpp、step2.cpp、step3.cpp、bfs.cppとmemo.mdとなります。
memo.md内に各ステップで感じたことを追記します。