要求:记录每一层
思路:简单
/**
* 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>> levelOrder(TreeNode* root) {
if(!root)return {};
vector<vector<int>> v;
queue<TreeNode*> q;
q.push(root);
int level=0;
while(!q.empty()){
v.push_back({});
int qsize=q.size();
while(qsize--){
TreeNode* tmp=q.front();
q.pop();
v[level].push_back(tmp->val);
if(tmp->left)q.push(tmp->left);
if(tmp->right)q.push(tmp->right);
}
++level;
}
return v;
}
};