leetcode102. 二叉树的层序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> ans;
    vector<int> level;
    queue<TreeNode*> q;
    vector<vector<int>> levelOrder(TreeNode* root) {
        if(!root)return ans;
        q.push(root);
        int count=1;
        while(q.size()){
            auto t=q.front();
            q.pop();
            count--;
            if(t->left)q.push(t->left);
            if(t->right)q.push(t->right);
            level.push_back(t->val);
            if(count==0){
                ans.push_back(level);
                level.clear();
                count=q.size();
            }
        }
        return ans;
    }
};