Open
Conversation
nodchip
reviewed
Jan 14, 2026
| if (node->left) nodes.push(node->left); | ||
| if (node->right) nodes.push(node->right); | ||
| } | ||
| result.push_back(current_level_values); |
| while (!nodes.empty()) { | ||
| int level_size = nodes.size(); | ||
| std::vector<int> current_level_values; | ||
| for (int i = 0; i < level_size; ++i) { |
There was a problem hiding this comment.
nodes の先頭 level_size 個を処理するという書き方は、 BFS の書き方としてはやや分かりにくいように感じます。 step1 のようにレベルごとに異なる配列を使うか、要素に深さも一緒に入れてあげるほうが分かりやすいと思います。
| if (!root) return {}; | ||
| std::vector<std::vector<int>> result; | ||
| std::vector<TreeNode*> nodes = {root}; // current-level nodes. | ||
| std::vector<TreeNode*> next_nodes; // next-level nodes. |
There was a problem hiding this comment.
next_nodes はループのイテレーション間で内容を持ち越さないため、スコープを短くするため、 while の中で定義したほうが良いと思いました。
| if (node->right) next_nodes.push_back(node->right); | ||
| } | ||
| result.push_back(current_level_values); | ||
| nodes = next_nodes; |
There was a problem hiding this comment.
std::swap(nodes, next_nodes) すると、コピーが発生しなくなり、やや軽くなると思います。
| class Solution { | ||
| public: | ||
| vector<vector<int>> levelOrder(TreeNode* root) { | ||
| if (!root) return {}; |
There was a problem hiding this comment.
こちらのコメントをご参照ください。
hemispherium/LeetCode_Arai60#10 (comment)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
102. Binary Tree Level Order Traversal
https://leetcode.com/problems/binary-tree-level-order-traversal/