/*
 * 演算法 / Algorithm: BFS with std::queue (廣度優先搜尋 + 佇列).
 * 每一輪外層迴圈用 q.size() 鎖定當前層的節點數，處理完剛好留下下一層。
 * Each outer loop uses q.size() to lock the current level's count, leaving
 * exactly the next level in the queue afterward.
 */

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> answer;          // 最終答案，每個元素是一層 / result; each element is one level
        if (root == nullptr) return answer;  // 空樹直接回空陣列 / empty tree → empty result

        queue<TreeNode*> q;                   // std::queue 是先進先出容器 / std::queue is a FIFO container
        q.push(root);                         // 根節點入列 / enqueue the root

        // 佇列非空代表還有下一層要處理。
        // A non-empty queue means another level remains.
        while (!q.empty()) {
            int size = q.size();              // 關鍵：先記本層節點數 / snapshot THIS level's node count
            vector<int> level;                // 收集本層的值 / values for this level
            level.reserve(size);              // 預留空間避免多次重新配置 / reserve to avoid reallocations (小優化 / minor optimization)

            // 正好處理 size 個節點 = 完整一層。
            // Process exactly `size` nodes = one full level.
            for (int i = 0; i < size; ++i) {
                TreeNode* node = q.front();   // 看佇列最前面的節點 / read the front node
                q.pop();                      // 把它移出佇列 / remove it from the queue
                level.push_back(node->val);   // 記下它的值 / record its value

                // 子節點屬於下一層，推到佇列尾。
                // Children belong to the next level; push them to the back.
                if (node->left)  q.push(node->left);   // 有左子節點才入列 / enqueue left child if present
                if (node->right) q.push(node->right);  // 有右子節點才入列 / enqueue right child if present
            }

            answer.push_back(move(level));    // 本層完成，收進答案；move 避免複製 / append level; move() transfers instead of copying
        }

        return answer;                        // 回傳逐層結果 / return level-by-level result
    }
};
