class Solution {
public:
    /*void traverse(TreeNode* root, vector<vector<int>>& res, int depth) {
        if(root){
            //新的一层
            ---if(res.size() < depth)  
                res.push_back(vector<int>{}); 
            //vector从0开始计数因此减1,在节点当前层的vector中插入节点
            res[depth - 1].push_back(root->val);
        }
        else
            return;
        //递归左右时进入下一层
        traverse(root->left, res, depth + 1); 
        traverse(root->right, res, depth + 1);
    }
    */
    vector<vector<int> > levelOrder(TreeNode* root) {
        /*vector<vector<int> > res;
        if(root == NULL)
            //如果是空,则直接返回空vector
            return res; 
        traverse(root, res, 1);
        return res;*/

        vector<vector<int>> res;
        if(root==nullptr) return res;

        queue<TreeNode*> q;
        q.push(root);
        
        while(!q.empty())
        {
            int l=q.size();
            vector<int> cur;

            for(int i=0;i<l;i++)
            {
                TreeNode* node=q.front();
                q.pop();
                cur.push_back(node->val);

                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
            }
            res.push_back(cur);
        }
        return res;
    }
};