剑指 Offer 32 - II. 从上到下打印二叉树 II - 力扣(LeetCode) (leetcode-cn.com)
利用队列的长度作为内循环。。。。。。
class Solution {
vector<vector<int>>res;
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if(root==nullptr) return res;
fun(root);
return res;
}
void fun(TreeNode*root){
if(root==nullptr) return;
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
int count=q.size();
vector<int>temp;
while(count--){
root=q.front();
q.pop();
temp.push_back(root->val);
if(root->left){
q.push(root->left);
}
if(root->right) q.push(root->right);
}
res.push_back(temp);
}
}
};