/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 * };
 */

class Solution {
  public:
    /**
     *
     * @param root TreeNode类
     * @return int整型vector<vector<>>
     */
    vector<vector<int> > levelOrderBottom(TreeNode* root) {
        // write code here
        vector<vector<int>> result;
        if (!root) return result;

        queue<TreeNode*> q;  // 用于层序遍历
        q.push(root);

        while (!q.empty()) {
            int levelSize = q.size();  // 当前层的节点数量
            vector<int> currentLevel;

            for (int i = 0; i < levelSize; i++) {
                TreeNode* node = q.front();
                q.pop();
                currentLevel.push_back(node->val);  // 保存当前层的节点值

                // 将子节点加入队列
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
            }

            result.push_back(currentLevel);  // 将当前层添加到结果中
        }

        // 反转结果以实现从底层到顶层的顺序
        reverse(result.begin(), result.end());
        return result;
    }
};