感觉我这个思路好 先记录上一层有几个节点

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> res;
        vector<int> path;
        queue<TreeNode*> q;
        if(!root)   return res;
        q.push(root);
        while(!q.empty()){
            int len=q.size();
            while(len--){
                TreeNode* tem=q.front();
                q.pop();
                path.push_back(tem->val);
                
                if(tem->left!=NULL) q.push(tem->left);
                if(tem->right!=NULL) q.push(tem->right);
            }
            res.push_back(path);
            path.clear();
        }
        return res;
    }
};