Conversation
Added detailed problem analysis, solution approaches, and code examples for calculating the maximum depth of a binary tree.
| int level_size = q.size(); | ||
| ++depth; | ||
|
|
||
| for (int i = 0; i < level_size; ++i) { |
There was a problem hiding this comment.
現在のレベルのサイズを固定してそこまで回す方法も良いですが、別々のキューを使う方法の方が可読性に優れると感じます。
内側のループを while(!q.empty()) で回し、最後に q = next_q; (または move、swap) とする方法です。
while (!q.empty()) {
std::queue<TreeNode*> next_q;
++depth;
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node->left != nullptr) {
next_q.push(node->left);
}
if (node->right != nullptr) {
next_q.push(node->right);
}
}
q = std::move(next_q);
}あと、BFS をするのに
node_queue
num_node_in_level
で数を数えて、次のレベルに行くの、少しややこしいと思っています。データの整合性が取れているということは、読んでいる人からすると全部読み終わらないと分からないからです。書いている人は分かるわけですが。
つまり、一つの変数に、2つの違う種類のものを入れておいて、その境界を個数で管理しているわけですよね。
https://discord.com/channels/1084280443945353267/1201211204547383386/1219179255615717399
| TreeNode* node = q.front(); | ||
| q.pop(); | ||
| if (node->left != nullptr) { | ||
| q.push(node->left); | ||
| } |
There was a problem hiding this comment.
NULLチェックですが、push前にやる方法のほか、pop直後にやる方法もあります。
q.pop(); の後に、if (node == nullptr) continue; と書くイメージです。上の再帰関数の方法は実質後者のパターンですね。
Co-authored-by: t9a-dev <t9a.dev@icloud.com>
| return 0; | ||
| } | ||
|
|
||
| std::queue<TreeNode*> q; |
There was a problem hiding this comment.
キューとdepthをpairでまとめる書き方もあります。
pairでまとめると、whileの中のループがなくなります。
| if (root == nullptr) { | ||
| return 0; | ||
| } | ||
| return std::max(maxDepth(root->left), maxDepth(root->right)) + 1; |
There was a problem hiding this comment.
この書き方と,Step1の書き方のどちらが良いか(1行にまとめる処理の最大数はどれくらいか)は好みが分かれるところだと思います.私はこのくらいならStep2の方がわかりやすいと感じます.
| return 0; | ||
| } | ||
|
|
||
| std::queue<TreeNode*> q; |
There was a problem hiding this comment.
変数名のみから中身が想像できるのが好みですが,これくらいのコードなら問題ないとも思います.
私はDFSやBFSには「探索完了ノードと未完了ノードの境界」=「探索の最前線」という解釈でfrontierという変数名を用いるのが好みです.
| if (root == nullptr) { | ||
| return 0; | ||
| } |
There was a problem hiding this comment.
docto-rinさんが言及されていた「Nullチェックをpop直後に行う」スタイルをとるとこの例外処理は省略可能ですね.
This: https://leetcode.com/problems/maximum-depth-of-binary-tree/
Next: https://leetcode.com/problems/minimum-depth-of-binary-tree/description/