Skip to content

102. Binary Tree Level Order Traversal#31

Open
ryosuketc wants to merge 1 commit intomainfrom
102_binary_tree_level_order_traversal
Open

102. Binary Tree Level Order Traversal#31
ryosuketc wants to merge 1 commit intomainfrom
102_binary_tree_level_order_traversal

Conversation

@ryosuketc
Copy link
Owner

if (node->left) nodes.push(node->left);
if (node->right) nodes.push(node->right);
}
result.push_back(current_level_values);
Copy link

Choose a reason for hiding this comment

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

インデントがずれているようです。

while (!nodes.empty()) {
int level_size = nodes.size();
std::vector<int> current_level_values;
for (int i = 0; i < level_size; ++i) {
Copy link

Choose a reason for hiding this comment

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

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.
Copy link

Choose a reason for hiding this comment

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

next_nodes はループのイテレーション間で内容を持ち越さないため、スコープを短くするため、 while の中で定義したほうが良いと思いました。

if (node->right) next_nodes.push_back(node->right);
}
result.push_back(current_level_values);
nodes = next_nodes;
Copy link

Choose a reason for hiding this comment

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

std::swap(nodes, next_nodes) すると、コピーが発生しなくなり、やや軽くなると思います。

class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if (!root) return {};
Copy link

Choose a reason for hiding this comment

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

こちらのコメントをご参照ください。
hemispherium/LeetCode_Arai60#10 (comment)

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.

2 participants