重点是,每次首先判断这个队列所剩的元素(那一层所有元素),然后再循环时,弹出,入值,然后放入对应得子孙。一遍循环结束,层的结果放入最终数组中,然后依次一层层走就可以了。

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

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

        vector<vector<int>> results;

        if(!root){
            return results;
        }

        queue<TreeNode* > Q;
        Q.push(root);

        int layer = 0;

        while(!Q.empty()){

            int size = Q.size();
            vector<int> layer_result;

            while(size--){
                TreeNode* node = Q.front();
                Q.pop();
                layer_result.push_back(node->val);

                   if(node->left) Q.push(node->left);
                   if(node->right) Q.push(node->right);
           }
            results.push_back(layer_result);

          }

         return results;
    }
};